Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq group by, order by

Tags:

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() 
like image 439
Nate Pet Avatar asked Feb 03 '12 17:02

Nate Pet


2 Answers

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); 
like image 124
vc 74 Avatar answered Sep 21 '22 13:09

vc 74


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()); 
like image 42
Amy B Avatar answered Sep 20 '22 13:09

Amy B