Question

So I use a command to save variables into a serialized file. I save the following data:

data.Save("ships", this.ships.Select(x => x.Name));

This is supposed to output an IEnumerable but instead it seems to output something different, which I'm guessing is to do with Lambda's lazy init? The error being:

Type 'System.Linq.Enumerable+WhereSelectListIterator`2[[~~~],[~~~]]' in Assembly '~~~' is not marked as serializable.

The error is caused due to the fact that this.ships is a non-serializable type, compared to the return of .Name of type string which it should be.

So I was hoping I could find out how to make it return it's true value?

I have realised that adding .ToList() would work, but I was curious for the neater solution.

Was it helpful?

Solution

System.Linq.Enumerable.WhereSelectListIterator<TSource, TResult> does implement IEnumerable<TResult> and, as you already know, it is not serializable.

WhereSelectListIterator stores the source and query definition, and allows your query to be lazy, what means it's evaluated when you need the results, not when the query is created.

If you want to serialize results of the query, you have to force the evaluation. Either ToList() or ToArray will work just fine.

data.Save("ships", this.ships.Select(x => x.Name).ToList());

To make sure that kind of error does not occur in future, you can consider changing Save method definition to use ICollection<T> instead of IEnumerable<T>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top