Select all columns but group by only one in linq

c# entity-framework linq sql-server

Question

I was seeking for information on how to acquire several columns but only group by one in SQL. I haven't been able to think of a method to accomplish it in Linq, however.

I have the following table with toys on it:

| Id | Message | GroupId | Date |
|-------------------------------|
| 1  | Hello   | 1       | 1:00 |
| 2  | Hello   | 1       | 1:01 |
| 3  | Hey     | 2       | 2:00 |
| 4  | Dude    | 3       | 3:00 |
| 5  | Dude    | 3       | 3:01 |

Additionally, I want to restore all columns for rows with separate values.GroupId as follows (in order by "Date" desc):

| Id | Message | GroupId | Date |
|-------------------------------|
| 1  | Hello   | 1       | 1:00 |
| 3  | Hey     | 2       | 2:00 |
| 4  | Dude    | 3       | 3:00 |

As long as it is the sole row assigned that group ID, I don't really care which row is chosen among the grouped ones (first, second, etc.).

I have so far developed the following code, however it does not function as intended:

List<XXX> messages = <MyRep>.Get(<MyWhere>)
                            .GroupBy(x => x.GroupId)
                            .Select(grp => grp.OrderBy(x => x.Date))
                            .OrderBy(y => y.First().Date)
                            .SelectMany(y => y).ToList();
1
6
8/11/2016 10:37:14 AM

Accepted Answer

ZZZ_tmp
14
8/11/2016 10:33:58 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow