0

I have the following class:

class MyClass{
    string field1, field2;
}

And I have List<MyClass> thats contains the following:

list.Add(new MyClass("1","1"));
list.Add(new MyClass("1","2"));
list.Add(new MyClass("1","3"));
list.Add(new MyClass("2","2"));
list.Add(new MyClass("3","2"));

I want to find the most frequent value of field1, this case I have three times the value "1", one time the value "2" and one time the value "3", How can I get the maximum count value of field1 (this case is "1")?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Ya Ko
  • 509
  • 2
  • 4
  • 19

2 Answers2

6

You can use LINQ for this.

string result = list.GroupBy(entry => entry.field1)
    .Max(item => item.Count());

But you have to make at least field1 public because you can not access it otherwise.

And your class MyClass does not have a constructor to create instances like you do it in your sample code ;)

If there are more then one element with the same number of entries you have to use something like this.

int maxCount = list.GroupBy(entry => entry.Field1)
    .OrderByDescending(grouping => grouping.Count())
    .First()
    .Count();

List<string> result = list.GroupBy(entry => entry.Field1)
    .Where(item => item.Count() == maxCount)
    .Select(x => x.Key)
    .ToList();

I splitted the statement because I think it's better to understand and easier to read.

Have a look at 101 LINQ Samples for more information.

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
1

If there is only one field1 value which would have max occurrences ( as in example in OP), a simple GroupBy followed by OrderByDescending would help you.

var maxOccuranceItem = list.GroupBy(x => x.field1)
                          .OrderByDescending(x => x.Count())
                          .First().Key;

Output

1

But,if there are two set of field1, which has same number of occurrences (in case of tie), I would use following

Scenario

list.Add(new MyClass("1","2"));
list.Add(new MyClass("1","3"));
list.Add(new MyClass("2","2"));
list.Add(new MyClass("2","2"));
list.Add(new MyClass("3","2"));

Solution for multiple items having max occurrences.

var grouped = list.ToLookup(x => x.field1);
var maxOccuranceCount = grouped.Max(x => x.Count());
var maxOccuranceItems = grouped.Where(x => x.Count() == maxOccuranceCount)
                              .Select(x => x.Key).ToList(); 

Output

1 
2 

In either case,as others have mentioned, the property needs to be public.

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51