简体   繁体   English

在列表中查找最常出现的项目的方法

[英]Method for finding most often occurring item in a list

Ok, so I have a project about a carpark. 好吧,所以我有一个关于停车场的项目。 Long story short I need a method to find most often occurring model in a data list. 长话短说,我需要一种在数据列表中找到最常出现的模型的方法。 Any good ways to approach this (Using VST 2012) 解决此问题的任何好方法(使用VST 2012)

private static int FilterbyModel(string Model, List<Car> cars)


  {
        int modelCount = 0;
        List<string> Modelis = new List<string>();
        foreach (Car s in cars)
        {
            if (s.Modelis == Model)
            {
                if (!Model.Contains(s.Modelis)) 
                {
                    Modelis.Add(s.Modelis);
                    modelCount++;
                }
            }
            return modelCount;

Above method would work, but I need to provide a specific model to look for rather than to just find the most common one. 上面的方法可以用,但是我需要提供一种特定的模型来寻找而不是仅仅找到最常见的模型。

Simplest way to count occurrences is to group by model and then count each group's elements. 计算发生次数的最简单方法是按模型分组,然后对每个分组的元素进行计数。 Here I give an example with LINQ: 这里我以LINQ为例:

var carsByModel = cars.GroupBy(x => x.Model)
    .Select(x => new { Model = x.Key, Count = c.Count() });

Now if you want to order them and pick the most common one: 现在,如果要订购它们并选择最常见的一种:

var mostCommonCar = carsByModel.OrderByDescending(x => x.Count).First();

If, for example, you need to print the two most common models: 例如,如果您需要打印两个最常见的模型:

foreach (var model in carsByModel.OrderByDescending(x => x.Count).Take(2))
    Console.WriteLine($"{model.Model}: {model.Count}");

Or the less common twos: 或不太常见的二元:

foreach (var model in carsByModel.OrderBy(x => x.Count).Take(2))
    Console.WriteLine($"{model.Model}: {model.Count}");

If in that count you're interested in one specific model you may do this (note that I do omit StringComparer in this example but I always suggest to use it in production code): 如果在这种情况下您对某个特定模型感兴趣,则可以这样做(请注意,在此示例中我确实省略了StringComparer ,但我始终建议在生产代码中使用它):

carsByModel.First(x => x.Model.Equals("modelYouWant"));

However note that if you just need to count occurrences of a specific model then this is faster and simpler: 但是请注意,如果您只需要计算特定模型的出现次数,那么它会更快,更简单:

int occurencesOfModelIWant = cars.Count(x => x.Model.Equals("modelYouWant"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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