Considering the following records:
Id F1 F2 F3
-------------------------------------------------
1 Nima 1990 10
2 Nima 1990 11
3 Nima 2000 12
4 John 2001 1
5 John 2002 2
6 Sara 2010 4
I want to group by based on the F1
field and sort by Id
and get all fields from the first record of group similar to these records:
Id F1 F2 F3
-------------------------------------------------
1 Nima 1990 10
4 John 2001 1
6 Sara 2010 4
How can I do this using linq?
This question is related to
c#
linq
c#-4.0
linq-to-entities
var result = input.GroupBy(x=>x.F1,(key,g)=>g.OrderBy(e=>e.F2).First());
Use it to achieve what you want. Then decide which properties you want to return.
yourList.OrderBy(l => l.Id).GroupBy(l => new { GroupName = l.F1}).Select(r => r.Key.GroupName)
var res = (from element in list)
.OrderBy(x => x.F2).AsEnumerable()
.GroupBy(x => x.F1)
.Select()
Use .AsEnumerable() after OrderBy()
The awnser of @Alireza is totally correct, but you must notice that when using this code
var res = from element in list
group element by element.F1
into groups
select groups.OrderBy(p => p.F2).First();
which is simillar to this code because you ordering the list and then do the grouping so you are getting the first row of groups
var res = (from element in list)
.OrderBy(x => x.F2)
.GroupBy(x => x.F1)
.Select()
Now if you want to do something more complex like take the same grouping result but take the first element of F2 and the last element of F3 or something more custom you can do it by studing the code bellow
var res = (from element in list)
.GroupBy(x => x.F1)
.Select(y => new
{
F1 = y.FirstOrDefault().F1;
F2 = y.First().F2;
F3 = y.Last().F3;
});
So you will get something like
F1 F2 F3
-----------------------------------
Nima 1990 12
John 2001 2
Sara 2010 4
Source: Stackoverflow.com