views:

36

answers:

3

Hi. I'm using a BinaryFormatter to serialize my object. I have various object types in their relevant lists. Is there a 'best' way to serialize all the objects into one file, but be able to separate them on deserialization? At the moment, I'm deserializing the whole file and checking a specific field in each object to see what list I should re-add them to after deserialization. For example all my Ford cars have the 'FORD' field, Toyota have 'TOYOTA' etc.. Upon deserialization, I 'foreach' through the objects, check their 'company' field and then assign them to a List<Company>.

I'm not sure if this is the most efficient way of doing things. Any suggestions? Thanks for the help

+3  A: 

This one's easy ... instead of serializing each individual item. Just make a "parent" class which simply has a property for each item type. And then you can serialize that one object. When you deserialize it on the other end it will already be full sorted out for you.

Joel Martinez
A: 

The only way that you could do this more efficiently is to serialize them into different files (based on a field criteria that makes sense to your domain). Because you are not guaranteed that they are going to be serialized into the file in a specific order, you'll have to read the entire file into memory when you deserialize anyways to find all instances of the type where the field value is what you are looking for.

I think you're already doing the best that you will within the constraints for serializing to a file. Have you considered SQLite to be your storage mechanism?

Dave White
A: 

What you are doing sounds like a dictionary (Dictionary<string, List<Company>>). Please provide some source code in your question, though.

There is no built-in way to serialize a dictionary, but you can make your own custom class. I'll leave that as an exercise to you to google that :)

If you want to continue to serialize the same way, but separate by a known member that is inside the objects (and the member is always the same), you can use a LINQ query to extract the objects with short code:

IEnumerable<Company> companiesFromFile = GetDeserializedFile();
var dictionaryFromFile = companiesFromFile.ToDictionary(c => c.Name);

Then, if you have to separate the lists, you can do it via:

List<Company> toyotaList = dictionaryFromFile["Toyota"];
// etc
Merlyn Morgan-Graham