Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert IEnumerable<T> to List<T> in C#?

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

Simplified code:

Dictionary<Guid, Record> dict = GetAllRecords();
myListView.DataSource = dict.Values.Where(rec => rec.Name == "foo");
myListView.DataBind();

I thought that would work but in fact it throws a System.InvalidOperationException:

ListView with id 'myListView' must have a data source that either implements ICollection or can perform data source paging if AllowPaging is true.

In order to get it working I have had to resort to the following:

Dictionary<Guid, Record> dict = GetAllRecords();
List<Record> searchResults = new List<Record>();

var matches = dict.Values.Where(rec => rec.Name == "foo");
foreach (Record rec in matches)
    searchResults.Add(rec);

myListView.DataSource = searchResults;
myListView.DataBind();

Is there a small gotcha in the first example to make it work?

(Wasn't sure what to use as the question title for this one, feel free to edit to something more appropriate)

like image 971
Christian Hagelid Avatar asked Aug 28 '08 05:08

Christian Hagelid


People also ask

Can you convert IEnumerable to List?

In C#, an IEnumerable can be converted to a List through the following lines of code: IEnumerable enumerable = Enumerable. Range(1, 300); List asList = enumerable. ToList();

How do I get IEnumerable to a List?

Use the ToList() Method to Convert an IEnumerable to a List in C# Enumerable. ToList(source); The method ToList() has one parameter only.

What's the difference between IEnumerable T and List t?

IEnumerable is read-only and List is not. IEnumerable types have a method to get the next item in the collection. It doesn't need the whole collection to be in memory and doesn't know how many items are in it, foreach just keeps getting the next item until it runs out.

Is IEnumerable better than List?

IEnumerable is more efficient and faster when you only need to enumerate the data once. The List is more efficient when you need to enumerate the data multiple times because it already has all of it in memory.


1 Answers

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.

like image 189
Matt Hamilton Avatar answered Sep 21 '22 01:09

Matt Hamilton