I have a Colour table like this:
Id Name VendorId
--------------------
1 Purple NULL
2 Blue NULL
3 Black NULL
4 Purple 1
5 Orange 1
6 Mauve 2
And I want to get all colours with VendorId as NULL, unless that colour Name has an entry with a VendorId attached, so e.g. for VendorId = 1 I'd like
Id Name VendorId
--------------------
2 Blue NULL
3 Black NULL
4 Purple 1
5 Orange 1
Noting that the Purple row Id 1 with the NULL VendorId is not on the list. For Id = 2 I'd get the rows 1,2,3 and 6
I thought initially to .Select .Distinct on Name but I need the entire object or at least the Id's
var result = _context.Colours
.Where(x => x.Vendor == null || x.Vendor.Id == vendorId)
.Select(x => x.Name)
.Distinct()
.ToList();
but if I use .Select(x => x.Id).Distinct() on then I get two instances of Purple
How can I achieve this in LINQ?
Edit:
I've just tried using
var result = _context.Colours
.Where(x => x.Vendor == null || x.Vendor.Id == vendorId)
.OrderByDescending(x => x.Id)
.GroupBy(x => x.Name)
.Distinct()
.ToList()
.Select(x => x.First())
.ToList();
Trying to get all null and id = 1, then order by descending Id and trying .GroupBy but I got Client side GroupBy is not supported.
