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.
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly