Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 693
Ken Ma Avatar asked Feb 10 '11 05:02

Ken Ma


1 Answers

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();
like image 192
Anthony Pegram Avatar answered Oct 20 '22 12:10

Anthony Pegram