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 null
s?
To get something like: {elements_with_date_1, elements_with_date_2, ..., elements_with_no_date}
?
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:
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With