.NET – missing methods – LINQ

Sometimes it makes me wonder why .NET doesn’t have some methods that really should be there.
string.IsNullOrWhiteSpace() just showed up in .NET 4 – should’ve been there ages ago.
For whatever reason the static extension methods aren’t allowed (nor extension properties.. come on, those _are_ methods.. Give’em to me!), so defining your own is not an option.
That is, I can create a static StringEx class full of utility methods, but extensions just look cleaner.

Anyways, one method LINQ is certainly missing is ToList() on old, non-generic IEnumerable.

        public static List<T> ToList<T>(this IEnumerable enumerable)
        {
            if (enumerable == null) throw new ArgumentNullException("enumerable");
            List<T> list = new List<T>();
            foreach (var item in enumerable)
            {
                T obj = (T)item; 
                list.Add(obj);
            }
            return list;
        }

Simple as that. I have to declare a resulting type on a method, so what. In VS extensions development, where a lot of properties are IEnumerables – this method sees a lot of use. And yeah, once it’s a list (or you could make it array, or whatever) – I can LINQ-query it, yeay!

You can see this method in use in my previous post – How to list all ProjectItems in Project   

 

EDIT:

Actually, I was wrong. The code above behaves very much like a Cast method from LINQ. Either Cast() or OfType() methods should be used.

Leave a Reply

Your email address will not be published. Required fields are marked *