Insights and discoveries
from deep in the weeds

Wednesday, December 22, 2010

Returning a derived list type from a LINQ query

I asked this question on StackOverflow and came up with a nifty little solution to the problem, generally.

LINQ will always return IEnumerable and has a method, ToList(), which converts to a generic list. This is great, but what if your initial list is not a generic list? Often I'll create classes that inherit generic lists but add some functionality or metadata specific to the list. It's inconvenient to rebuild the list in the original type each time you do a LINQ query, or create a special method for each class to do this.

So I ended up creating a generic extension method which lets you automatically cast your results into any IList object, as follows:

public static T ToList(this IEnumerable baseList) where T : IList,new()
    T newList = new T();
    foreach (object obj in baseList)
    return (newList);

Now you can just do this:

MyListClass newList = oldList.Where(item=>item.SomeProperty=SomeValue).ToList();

Problem solved.

No comments:

Post a Comment