Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to check for elements in list?

If I want to perform actions such as .Where(...) or .Max(...), I need to make sure the list is not null and has a count greater than zero. Besides doing something such as the following everytime I want to use the list:

if(mylist != null && mylist.Count > 0)
{...}

is there something more inline or lambda like technique that I can use? Or another more compressed technique?

like image 971
4thSpace Avatar asked Nov 09 '11 16:11

4thSpace


2 Answers

public static class LinqExtensions
{
     public static bool IsNullOrEmpty<T>(this IEnumerable<T> items)
     {
           return items == null || !items.Any();
     }
}

You can then do something like

if (!myList.IsNullOrEmpty())
 ....
like image 183
Muhammad Hasan Khan Avatar answered Sep 28 '22 20:09

Muhammad Hasan Khan


My general preference is to have empty list instances, instead of null list variables. However, not everyone can cajole their co-workers into this arrangment. You can protect yourself from null list variables using this extension method.

public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
{
  return source ?? Enumerable.Empty<T>();
}

Called by:

Customers result = myList.EmptyIfNull().Where(c => c.Name == "Bob");

Most linq methods work on empty collections. Two methods that don't are Min and Max. Generally, I call these methods against an IGrouping. Most IGrouping implementations have at least one element (for example, IGroupings generated by GroupBy or ToLookup). For other cases, you can use Enumerable.DefaultIfEmpty.

int result = myList.EmptyIfNull().Select(c => c.FavoriteNumber).DefaultIfEmpty().Max();
like image 33
Amy B Avatar answered Sep 28 '22 18:09

Amy B