Nate Pet
Nate Pet

Reputation: 46222

linq group by, order by

I have the following list

ID  Counter  SrvID FirstName
--  ------   ----- ---------  
1   34       66M   James
5   34       66M   Keith
3   55       45Q   Jason
2   45       75W   Mike
4   33       77U   Will

What I like to do is to order by ID by ascending and then get the first value of Counter, SrvID which are identical (if any).

So the output would be something like:

ID  Counter  SrvID FirstName
--  ------   ----- ---------  
1   34       66M   James
2   45       75W   Mike
3   55       45Q   Jason
4   33       77U   Will

Note how ID of 5 is removed from the list as Counter and SrvID was identical to what I had for ID 1 but as ID 1 came first I removed 5.

This is what I would do but not working

    var result = (from ls in list1
                  group ts by new {ls.Counter, ls.SrvID}
                order by ls.ID
                  select new{
                             ls.ID,
                             ls.Counter.FirstOrDefault(),
                             ls.SrvID.First,
                             ls.FirstName}).ToList()

Upvotes: 27

Views: 83147

Answers (2)

Amy B
Amy B

Reputation: 110111

Group the records up, and pick a winner from each group.

var query =
  from record in list1
  group record by new {record.Counter, record.SrvID } into g
  let winner =
  (
    from groupedItem in g
    order by groupedItem.ID
    select groupedItem
  ).First()
  select winner;

var otherQuery = list1
  .GroupBy(record => new {record.Counter, record.SrvID })
  .Select(g => g.OrderBy(record => record.ID).First());

Upvotes: 27

vc 74
vc 74

Reputation: 38179

list1.GroupBy(item => new { Counter = item.Counter, SrvID = item.SrvID })
     .Select(group => new { 
        ID = group.First().ID, 
        Counter = group.Key.Counter,
        SrvID = group.Key.SrvID,
        FirstName = group.First().FirstName})
     .OrderBy(item => item.ID);

Upvotes: 44

Related Questions