Nate Pet
Nate Pet

Reputation: 46222

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.

Upvotes: 1

Views: 1741

Answers (2)

Adrian Iftode
Adrian Iftode

Reputation: 15663

The funny thing is the full error message is:

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

Upvotes: 3

Aducci
Aducci

Reputation: 26644

I have had a problem with using First in Entity Framework, have you tried changing to FirstOrDefault ?

Upvotes: 2

Related Questions