0
votes

I have following LINQ statement:

    string[] str = { "a", "ab", "abcd" };
    var s1 = from s in str.AsEnumerable()
             select s;
    ViewState.Add("str", s1);

I added s1 into ViewState and I got following error:

Type 'System.Linq.Enumerable+WhereSelectArrayIterator`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' in Assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.

How can I solve this problem and how can I add the LINQ variable into ViewState?

2
On a related note the ViewState is for storing state, i.e. selected value in a drop down, current page of a GirdView etc, not for putting data in.Ben Robinson

2 Answers

5
votes

You cannot do this directly, because whatever you do want to add to ViewState must be serializable (marked with SerializableAttribute) as the compiler is telling you. The runtime type of s1 is a nested generic class within System.Linq.Enumerable, which does not have that attribute.

One thing you could do is call .ToArray() (or another similar method) before adding the variable:

string[] str = { "a", "ab", "abcd" }; 
var s1 = from s in str.AsEnumerable() select s; 
ViewState.Add("str", s1.ToArray()); 

Of course, this is pointless as it stands because you could have achieved the same effect with just

string[] str = { "a", "ab", "abcd" }; 
ViewState.Add("str", str); 

Overall, it's not clear from the example what you are trying to achieve here.

1
votes

You already have an array, so store str in ViewState.

ViewState.Add("str", str);