linq group by,order by

时间:2012-02-03 17:38:41

标签: c# linq

我有以下列表

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

我喜欢做的是通过升序然后按ID排序 得到Counter,SrvID的第一个值是相同的(如果有的话)。

所以输出结果如下:

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

注意如何从列表中删除ID为5,因为Counter和SrvID与我对ID 1的相同,但ID 1首先出现 我删除了5。

这就是我会做但不工作

    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()

2 个答案:

答案 0 :(得分:34)

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);

答案 1 :(得分:22)

将记录分组,并从每个组中挑选一名获胜者。

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());