How to make Group by in Linq work with possible null values, in C#?


I am trying to add List.GroupBy(a=>a.ProductType.Name).Select(a=>a.FirstOrDefault()), now here I can have null values for .ProductType or .name so how can I ignore null values in C#, so I can get proper results of GroupBy?

If I am using above query in C#, I am getting error

Object reference not set to an instance of an object

I tried to make it like List.GroupBy(a=>a.ProductType != null ? a.ProductType), but it doesn't work.


Asked by:- Vinnu
0
: 9642 At:- 8/29/2019 3:12:09 PM
C# linq







1 Answers
profileImage Answered by:- pika

You can use null conditional operator in C# 6.0 and above to get rid of null error in GroupBy in Linq

List.GroupBy(a=>a?.ProductType?.Id)

In the above code, the ?. is the null-conditional operator, you can read more about it here

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators

Available in C# 6 and later, a null-conditional operator applies a member access, ?., or element access, ?[], operation to its operand only if that operand evaluates to non-null. If the operand evaluates to null, the result of applying the operator is null. The null-conditional member access operator ?. is also known as the Elvis operator.

Hope it helps.

1
At:- 9/17/2019 2:32:46 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use