开发者

How to use ToList on Collection<T>

开发者 https://www.devze.com 2023-03-31 09:09 出处:网络
MSDN documentation indicates the the class Collection<T>开发者_Python百科 has a method ToList() in the Extension section.

MSDN documentation indicates the the class Collection<T>开发者_Python百科 has a method ToList() in the Extension section.

How I can use this method?


This documentation is a bit misleading. The type Collection<T> doesn't have this method directly. Intstead it's defined as an extension method on System.Linq.Enumerable. Adding the using directive for System.Linq should fix the problem

using System.Linq; 

...

Collection<T> col = ...;
List<T> list = col.ToList();


Make sure you have a reference to System.Core.dll, and add, at the top of your C# file, using System.Linq;

You can see this in the documentation for ToList():

Namespace:  System.Linq
Assembly:  System.Core (in System.Core.dll)

Also, since the declaration is an extension method (this IEnumerable<TSource> source), you'll have to using the using statement to refer to it, as it's defined on a different type (Enumerable).


you call ToList() on an instance of it.

myCollection.ToList()

The extension method available on all types that implement IEnumerable<T>.

This requires using System.Linq in your cs file, and a reference to System.Core both of which are added by default in current versions of VS when targeting .net 3.5 or later.


Add this to the top of your file.

using System.Linq;


The ToList method is an extension method defined in the System.Linq namespace, so to use the method you must include a using statement to System.Linq. Once you do that, it's as simple as yourCollection.ToList().


ToList() is an extension method. Do you have the correct namespace (System.Linq) imported and referenced?


Sometimes a commandline project will not have a reference to System.Data.Linq in it, so even if you add a using statement, you won't get intellisense or proper compiling on the project. I.e. When you do like

Datacontext dc = new DataContext();
dc.Tablename.W

and when you start typing W you expect to see "where" but you don't. Adding a reference to the project fixes this.

Open "References" folder in your project. Look for a reference to System.Data.Linq. If it's not there, right click on the References folder, and select "Add Reference..." then click the .NET tab and look for System.Data.Linq, select it and hit OK. Everything should now work.

I use Where as an example, because that's where I always discover it, but the ToList() etc is the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消