Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ GroupBy with NULL values

Tags:

c#

linq

group-by

I have an object with some dates:

class MyObj
{
   public DateTime? Date {get; set;}
}

As you can see Date is nullable. Is it possible to use LINQ's GroupBy method to group a List<MyObj> by dates including nulls?

To get something like: {elements_with_date_1, elements_with_date_2, ..., elements_with_no_date}?

like image 213
Nickon Avatar asked Dec 24 '22 17:12

Nickon


2 Answers

It's not overly difficult to test it. Here's my code:

var items = new []
{
    new MyObj() { Date = null },
    new MyObj() { Date = null },
    new MyObj() { Date = DateTime.Now },
};

var grouped = items.GroupBy(x => x.Date);

I get this result:

result

like image 117
Enigmativity Avatar answered Dec 27 '22 07:12

Enigmativity


The GroupBy-method is an extension-method, which means it is a static method which accepts your date as a parameter. It is written as listWithNulls.GroupBy() but actually is treated as GroupBy(listWithNulls). Because of that behavior, null-values can be handled and you don't get a NullReferenceException.

Have a look at the extension-methods definition. It helps to understand how you can work with them:

public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);

You can see the first argument written as this IEnumerable<TSource> source, which enables the short-handle source.GroupBy().

like image 31
Patrik Avatar answered Dec 27 '22 05:12

Patrik