Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

Here is how I serialized to the 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 it's much the same but I just can't wrap my head around it.

like image 692
Matt Avatar asked Dec 17 '22 01:12

Matt


2 Answers

Use a MemoryStream instead of the file stream:

Stream s = new MemoryStream();

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

In order to read from it, you will need to set the Position to 0, so seeking will start from the beginning of the stream (if reading in chunks), or use ToArray() on it to retrieve the complete content.

like image 177
Oded Avatar answered Dec 24 '22 02:12

Oded


To put it bluntly: I would put them in another table in the database that has a one-to-many foreign-key relationship with its parent record.

That way, you can do normal DB operations with them, like retrieving parent records based on which ints are in the child table.

like image 25
Powerlord Avatar answered Dec 24 '22 02:12

Powerlord