-7

I need to find the person who has the maximum items in a list like this:

class Person
{
   var personid;
   var personname;
   var blah;
}

List<Person> people = new List<Person>(); 

Sample list

1 John
1 John
1 John
2 Smith
1 John

Sample result

1 3   (id, count)

Sample bonus result -with Top N clause

1 3
2 1

Plus; Top N clause would be nice if any/built-in. I would like to learn both versions; with or without Top clause.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
Nime Cloud
  • 6,162
  • 14
  • 43
  • 75

2 Answers2

1

I don't understand the first part of the question. What list?

For the second part: The linq equivalent to TOP in SQL is Take(). Combine it with Skip() to get the next X lines of the results.

Anders Abel
  • 67,989
  • 17
  • 150
  • 217
1

Max :

var biggestGrpOfPeopleHavingSamePersonId = 
people.GroupBy(x => x.personid).Max(x => x.Count());

Top :

var top3peopleGroups = 
people.GroupBy(x => x.personid).OrderByDescending(x => x.Count()).Take(3);

EDIT :

The first query returns an element of type IGrouping<TKey,TValue> where TKey is of the same type of personid and TValue is of type Person. The second query returns an IEnumerable<> of objects like that.

So, for example in the second case you can do:

foreach(var g in top3peopleGroups)
{
   Console.WriteLine("Person Id: " + g.Key + ", Count: " + g.Count());
}
digEmAll
  • 56,430
  • 9
  • 115
  • 140