I have a class like
public class Test
{
public string name;
public int status;
}
Example data
new Test("Name1", 1);
new Test("Name2", 2);
new Test("Name3", 3);
new Test("Name4", 1);
new Test("Name5", 2);
new Test("Name6", 2);
new Test("Name7", 3);
I'm looking for some linq to return the value 2 - which is the status that occurs the most.
Currently I have the following which is not correct.
var status = listTest.GroupBy(x => x.status).Select(x => x.OrderByDescending(t => t.status).First()).FirstOrDefault().status;
But hoping there is something cleaner?
CodePudding user response:
I think this is what you want
You need to order the groups themselves, not what is in each group.
var status = listTest
.GroupBy(x => x.Status)
.OrderByDescending(g => g.Count())
.FirstOrDefault()?.Key;
CodePudding user response:
You can group and pick the top after sorting them descending
var value = list.GroupBy(q => q.status)
.OrderByDescending(gp => gp.Count())
.First().Key;