i want to select distinct values from database based on one property with returned all values when that property is null
. IDs
in my database are Strings
My database looks like this:
Id1 Id2 Value
____________________
1 null Value1
2 1 Value2
3 1 Value3
4 null Value4
5 null Value5
6 2 Value6
7 2 Value7
8 2 Value8
I want to get output from my query like this:
Id1 Id2 Value
____________________
1 null Value1
2 1 Value2 // i dont care which one from Id2 = 1 i get
4 null Value4
5 null Value5
6 2 Value6 // i dont care which one from Id2 - 2 i get
As you can see i want to get a List
that have all elements where Id2
is null and return only one element where Id2
is the same (i dont care which element query will return).
I tried to code something:
query
.Where(x => !string.IsNullOrEmpty(x.Id2))
.GroupBy(z => z.Id2)
.Select(grp => grp.FirstOrDefault())
.ToListAsync();
But i dont get what i want, only one item representation by Id2
and only one null
value, something like this:
Id1 Id2 Value
____________________
1 null Value1
2 1 Value2 // I want to get all elements where Id2 = null
6 2 Value6 // and distinct elements based on Id2
My question is, how to write query to EF to get all null items and all distinct items based on property?