How can I convert IEnumerable to List in C#?

前端 未结 5 1812
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 07:14

I am using LINQ to query a generic dictionary and then use the result as the datasource for my ListView (WebForms).

Simplified code:

Dictionary

        
相关标签:
5条回答
  • 2020-12-29 07:52

    Try this:

    var matches = dict.Values.Where(rec => rec.Name == "foo").ToList();
    

    Be aware that that will essentially be creating a new list from the original Values collection, and so any changes to your dictionary won't automatically be reflected in your bound control.

    0 讨论(0)
  • 2020-12-29 07:54

    You might also try:

    var matches = new List<Record>(dict.Values.Where(rec => rec.Name == "foo"));
    

    Basically generic collections are very difficult to cast directly, so you really have little choice but to create a new object.

    0 讨论(0)
  • 2020-12-29 08:04

    Just adding knowledge the next sentence doesn´t recover any data from de db. Just only create the query (for that it is iqueryable type). For launching this query you must to add .ToList() or .First() at the end.

    dict.Values.Where(rec => rec.Name == "foo")
    
    0 讨论(0)
  • 2020-12-29 08:11

    I tend to prefer using the new Linq syntax:

    myListView.DataSource = (
        from rec in GetAllRecords().Values
        where rec.Name == "foo"
        select rec ).ToList();
    myListView.DataBind();
    

    Why are you getting a dictionary when you don't use the key? You're paying for that overhead.

    0 讨论(0)
  • 2020-12-29 08:12
    myListView.DataSource = (List<Record>) dict.Values.Where(rec => rec.Name == "foo");
    
    0 讨论(0)
提交回复
热议问题