LINQ group by and max clause usage -
i have below employee class has 3 important fields
public class employee { public string name { get; set; } public string department { get; set; } public double salary { get; set; } }
i have list of such employees. want find out name employee each department salary maximum in his/her department.
i wrote below query not working.
list<employee> list = new list<employee>(); list.add(new employee { name="hemant",salary=10,department="pts"}); list.add(new employee { name = "gunjan", salary = 11, department = "pts" }); list.add(new employee { name = "akshay", salary = 8, department = "pts" }); list.add(new employee { name = "omkar", salary = 10, department = "ebg" }); list.add(new employee { name = "hemant1", salary = 14, department = "ebg" }); var query1 = e in list group e e.department g select new { dept = g.key,maxsal = g.max((e) => e.salary )}; foreach (var item in query1) { console.writeline("department : " + item.dept + " : " + " salary : " + item.maxsal); }
but above piece of code not working, not able select employee name. think must use ascending/descending clause , select first or last record. not able figure out. can help.
regards, hemant shelar
yes, should orderbydescending
, first
:
var query1 = list.groupby(x => x.department) .select(g => g.orderbydescending(x => x.salary).first());
below console code:
foreach (var item in query1) { string output = string.format("deparment: {0}, name: {1}, max salaray: {2}", item.department, item.name, item.salary ); console.writeline(output); }
Comments
Post a Comment