Showing all posts tagged: 'Linq'

A 2-post collection

Ordering Collections with enum properties using LINQ

Posted in Linq, c#

Interesting find today. To order a collection based on an enum alphabetically, you can use LINQ as per the example below: var collection = new List<myCustomObjectWithEnumProperty>(); var sortedCollection = collection.OrderBy(c=>c.EnumProperty.ToString()); To order a collection based on an enum by value, you can do the following: var collection = new List<myCustomObjectWithEnumProperty>(); var sortedCollection = collection.OrderBy(c=>(int)c.EnumProperty); Simple as that! Happy coding... …[read more]


Checking if a generic collection is empty with Linq and C#

This is a common issue for many developers. How do you quickly and efficiently determine whether a given non-null collection contains any valid non-empty elements . The string class is cool because you can use the string.IsNullOrEmpty(yourstring); to test for null and/or empty. Unfortunately, generic collections don’t implement a similar method. There are two ways to deal with this. The first one requires you to write an extension for generic collections like this: public static bool IsEmpty<T>(this IEnumerable<T> list) { if (list is ICollection<T>) return ((ICollection<T& …[read more]