In C #, how can I serialize List <int> to byte [] to save it in the DB field?

In C #, how can I serialize a List<int> to byte[] to save it in a DB field?

I know how to serialize a file to disk, but how do I just serialize in a variable?

This is how I serialize to disk:

  List<int> l = IenumerableofInts.ToList(); Stream s = File.OpenWrite("file.bin"); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(s, lR); s.Close(); 

I'm sure this is almost the same, but I just can't hug my head around him.

+4
source share
4 answers

Use a MemoryStream instead of a file stream:

 Stream s = new MemoryStream(); 

This will put the data in the s variable, which you can read later in your application.

To read this, you need to set Position to 0, so the search will start at the beginning of the stream (if reading in pieces) or use ToArray() on it to get the full content.

+8
source

Let's face it: I would put them in another table in the database, which has a one-to-many foreign key relationship with the parent record.

Thus, you can perform normal DB operations with them, for example, get parent records based on what ints are in the child table.

+3
source

Personally, I would not use BinaryFormatter for this purpose - this implementation is specific and too expensive. I would be prone to (one of):

1: use BinaryWriter / BinaryReader for this manually (but note that it is easy to interpret from any API):

  // note I've used arrays in the example; lists are identical int[] data = { 1, 2, 3, 4, 5 }; byte[] raw; using (var ms = new MemoryStream()) using (var writer = new BinaryWriter(ms)) { writer.Write(data.Length); foreach(int i in data) { writer.Write(i); } writer.Close(); raw = ms.ToArray(); } // read it back using (var ms = new MemoryStream(raw)) using (var reader = new BinaryReader(ms)) { int count = reader.ReadInt32(); data = new int[count]; for (int i = 0; i < count; i++) { data[i] = reader.ReadInt32(); } } 

or 2: use an implementation-independent serialization format such as protobuf; here i am using protobuf-net

  int[] data = { 1, 2, 3, 4, 5 }; byte[] raw; using (var ms = new MemoryStream()) { Serializer.Serialize(ms, data); raw = ms.ToArray(); } // read it back using (var ms = new MemoryStream(raw)) { data = Serializer.Deserialize<int[]>(ms); } 

Note that (1) uses 24 bytes for example (6 * 4 bytes); (2) uses 10 bytes (partly because the numbers are simple, but actually protobuf has some tricks (like "packed" data) that we don’t even use here).

+1
source

Use universal serializer

 private static string SerializeObject<T>(T source) { var serializer = new XmlSerializer(typeof(T)); using (var sw = new System.IO.StringWriter()) using (var writer = new XmlTextWriter(sw)) { serializer.Serialize(writer, source); return sw.ToString(); } } 

http://weblogs.asp.net/rajbk/archive/2009/10/04/xmlserializer-and-invalid-xml.aspx

0
source

Source: https://habr.com/ru/post/1305244/


All Articles