Simple LINQ and List error: WhereListIterator`1[Task]' to type 'System.Collections.Generic.List`1[Task]'
Asked Answered
F

1

49

I'm having trouble understanding my error

Method:

public List<Task> GetAllTasks()
{
    var AllTasks = from t in tasks
                   where t.Status.ToString() == "Completed" || t.Status.ToString() == "Pending"
                   select t;

    return (List<Task>)AllTasks;
}

Code Behind:

protected void Page_Load(object sender, EventArgs e)
{
    TaskList tdl = (TaskList)Session["TodoList"];
    List<Task> AllTasks = tdl.GetAllTasks();
    string str = "";

    foreach (Task t in AllTasks)
    {
        str += t.ToString() + "<br />";
    }

    LblTasks.Text = str;

}

After I add a task (AddTask.aspx) I redirect to another page to display them, then I get the runtime error:

Unable to cast object of type 'WhereListIterator1[Task]' to type 'System.Collections.Generic.List1[Task]'.

Is there something wrong with my LINQ? I just learned yesterday hehe.

Thanks.

Ferreous answered 10/2, 2011 at 5:36 Comment(0)
D
93

You just need a .ToList() either directly on the query or when you return it. As in

var AllTasks = (from t in tasks
               where t.Status.ToString() == "Completed" || t.Status.ToString() == "Pending"
               select t).ToList();

Or

return AllTasks.ToList();
Dashtikavir answered 10/2, 2011 at 5:38 Comment(2)
Thanks alot! That works. I see the point of ToList(), but how come the typical cast doesn't work?Ferreous
@Ken, The LINQ querying methods are designed to work against any sequence implementing IEnumerable<T>, and they are lazily evaluated. The source being a List<T> isn't relevant. If you want concrete collections, they have provided methods to support that, such as ToArray(), ToList(), ToDictionary(), etc.Dashtikavir

© 2022 - 2024 — McMap. All rights reserved.