I have a LINQ to SQL query which at one point, returns two rows which I'd like to group by ID and select specific fields, lets say something like this:
ID | Field1 | Field2 | Field3
-----------------------------
1 | 2 | null | 4
1 | 3 | 5 | null
What's unusual about this query is that from the group, I want to select something like this:
ID | Field1 | Field2 | Field3
-----------------------------
1 | 2 | 5 | 4
Note that the group selects fields from both records. Also note that it's not a simple null coalesce type operation as I need to be able to select a Field1
of 2 or 3 based on some other factors (another field).
Is there a clever way I can project into a new type whilst selecting specific fields as I want them?
I'm working on an IQueryable
at this point, so I need a solution which translates into SQL, previously the query did something like this:
.Select(x => new MyObject {
Field1 = myGroup.First(x => x.Field4 == 1).Field1,
Field2 = myGroup.FirstOrDefault(x => x.Field4 == 1) == null ? myGroup.FirstOrDefault(x => x.Field4 == 2).Field2 : myGroup.FirstOrDefault(x => x.Field4 == 1).Field2
});
Which doesn't work as it can't work out what to with the operations.
I think we might be resigned to selecting some combination object with all the fields denormalised and then selecting from LINQ to objects in memory, but I'd rather have the DB do the work if possible.