0

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?

1
  • 1
    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. Commented Dec 20, 2011 at 12:42

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

ViewState.Add("str", str); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.