简体   繁体   中英

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

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.

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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