user957178
user957178

Reputation: 631

list<int> showing null

string[] baChildrenIds = ids.Split(',');
                    List<int> intList = new List<int>();
                    foreach (var id in baChildrenIds)
                    {
                        intList.Add(Convert.ToInt32(id));
                    }
                    List<int> tempList = new List<int>();
                    if (Session["SelectedList"] != null)
                    {
                        var temp = Session["SelectedList"] as List<int>;
                        tempList.AddRange(temp);
                    }
                    Session["SelectedList"] = tempList.Union(intList);

Initial Add I am adding two Integer values to the Session. second time I am adding three integer values to the Session.

when I am accessing the Session something like this I am allways getting null.

 var temp = Session["SelectedList"] as List<int>;

Could any body help me out? how to get all the session values as list?

Thanks

Upvotes: 0

Views: 379

Answers (5)

Vishal Patel
Vishal Patel

Reputation: 281

when you assign the session your session become System.Linq.Enumerable.UnionIterator<int> type and when you access the session you convert it in List<int> which is not match so it gives the error.

you have to write like as follow so you can get the value

if (Session["SelectedList"] != null)

  {

  List<int> ls = (List<int>)Session["SelectedList"];           
  var temp = ls;

  tempList.AddRange(temp);
  }

Session["SelectedList"] = tempList.Union(intList).ToList(); 

Upvotes: 1

KodeKreachor
KodeKreachor

Reputation: 8882

The Union Linq operation returns an IEnumerable. When assigning your session variable try this instead:

Session["SelectedList"] = tempList.Union(intList).ToList();

Upvotes: 2

Soe Moe
Soe Moe

Reputation: 3438

Session["SelectedList"] = tempList.Union(intList).ToList();

Union method returns IEnumerable, not List.

Hope it helps.

Upvotes: 2

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

The as operator returns null if the cast fails.

In your case Session["SelectedList"] isn't of type List<int>, so null is being returned.

The call to .Union isn't returning a List<int>, but an IEnumerable<int> instead. Call .ToList() to convert it to a List<int>

Upvotes: 2

Brannon
Brannon

Reputation: 5414

The List class doesn't have a Union method. That method is coming out of the LINQ extensions, and it returns IEnumerable in your case. IEnumerable is not a list. If you were using a cast rather than "as" you would have seen a runtime error. All you need to do is tack .ToList() onto the end of the last line.

Upvotes: 3

Related Questions