Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
923 views
in Technique[技术] by (71.8m points)

asp.net - 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.

question from:https://stackoverflow.com/questions/4953748/simple-linq-and-list-error-wherelistiterator1task-to-type-system-collectio

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...