简体   繁体   中英

Finding the “mode” of pairs of numbers

My relevant code looks something like this:

//The object

Class MyClass
{
     int PositionCount { get; set;}
     Value { get; set;}

     MyClass(int positionCount, double value)
     {
          PositionCount = positionCount;
          Value = value;
     }
}

//And then, later, using the object

List<MyClass> list = new List<MyClass>();

MyClass obj1 = new MyClass(18, 356.2);
list.Add(obj1);

MyClass obj2 = new MyClass(18, 356.2);
list.Add(obj2);

MyClass obj3 = new MyClass(19, 22.5);
list.Add(obj3);

MyClass obj4 = new MyClass(19, 30.325);
list.Add(obj4);

MyClass obj5 = new MyClass(19, 356.2);
list.Add(obj5);

What I'd like to find is the most common occurrence of number pairs in this list. Here, I'd expect to get back the values in obj1 and obj2, since they repeat two numbers each. I haven't had much luck with getting the modes of PositionCount and Value separately, as (in this case), the mode of PositionCount is 19 and Value is 356.2, but there is no pair (or more) of elements in the list with both of these numbers.

Thanks for any guidance.

Something like this:

var mostCommon = list
              .GroupBy(x=>new {x.PositionCount, x.Value})
              .OrderByDescending(x=>x.Count()).First();

It will group by your properties and then get that with biggest count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM