简体   繁体   English

linq通过First()分组

[英]linq group by First()

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). 我想做的是通过升序按ID排序,然后获得相同的Counter,SrvID的第一个值(如果有的话)。

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. 请注意,如何将ID 5从列表中删除,因为Counter和SrvID与我对ID 1的拥有相同,但是当ID 1首先出现时,我删除了5。

I tried the following but not working: 我尝试了以下操作,但不起作用:

     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; 

I get the followng message: The method 'First' can only be used as a final query operation. 我收到以下消息:方法“ First”只能用作最终查询操作。

有趣的是,完整的错误消息是:

"NotSupportedException: The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead."

我在实体框架中使用First遇到问题,您是否尝试过更改为FirstOrDefault

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM