简体   繁体   中英

How can I convert an IEnumerable<MyType> into a MyList<MyType>?

I have a custom List MyList that is an extension of List , and I have an IEnumerable (or IQueryable) which I want to do .ToList() on, but I guess, .ToMyList() .

How can I implement the ToList() method? The source code for ToList() is to create a new List() and pass in the IEnumerable as a parameter, but I am not sure what it does with it.

If your class subclasses List<T> , and you provide the correct constructor , you should be able to do:

MyList<MyType> list = new MyList<MyType>(theEnumerable);

If you want a simple extension method, similar to Enumerable.ToList , you could write your own:

public static MyList<T> ToMyList<T>(this IEnumerable<T> theEnumerable)
{
    return new MyList<T>(theEnumerable);
}

You could then call this via:

var list = theEnumerable.ToMyList();

Note that subclassing List<T> , in general, is really not a very good idea. You should really consider subclassing Collection<T> and implementing IList<T> , if you need a custom collection, instead. You can still provide the same constructors and use the methods above to populate the custom collection, if required.

If you have a base class and you are able to delegate list population to its constructor, do that:

public MyList(IEnumerable<MyType> items) : base(items) { }

Otherwise, this constructor should work for almost any collection class:

public MyList(IEnumerable<MyType> items)
{
    if (items == null)
        throw new ArgumentNullException("items");

    foreach (var item in items)
        Add(item);
}

Then you can write an extension method, or call this constructor directly to populate a new list from a sequence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM