c# - 在 C# 中查找列表中的多个重复值

标签 c# list

那么,假设我有一份汽车 list 。列表中的每个项目都有一个品牌和一个颜色属性。我想找出每个品牌有多少相同颜色的品牌,然后打印该信息。该列表将由用户输入填充。我无法确定列表中将包含哪些确切值。

例子:

class Car
    {
        public string brand;
        public string color;
    }

    private void DoSomething()
    {
        List<Car> cars = new List<Car>();
        cars.Add(new Car { brand = "Toyota", color = "blue" });
        cars.Add(new Car { brand = "Toyota", color = "red" });
        cars.Add(new Car { brand = "Toyota", color = "blue" });
        cars.Add(new Car { brand = "Audi", color = "red" });
        cars.Add(new Car { brand = "Audi", color = "red" });
        cars.Add(new Car { brand = "Audi", color = "blue" });

        // Find out for each brand how many there are of the same color, and then print that info
        // Example output: Toyota: 2 blue, 1 red
        //                 Audi:   2 red, 1 blue
    }

我花了很长时间寻找一种方法来做到这一点。我所能弄清楚的是如何获得列表中某个项目的出现次数。

如果我的问题不清楚,请告诉我,我会尝试解释更多。

最佳答案

一些 linq 应该这样做:

var result = cars.GroupBy(x => new { x.brand, x.color })
    .Select(x => new { 
        Brand = x.Key.brand, 
        Color = x.Key.color, 
        Count = x.Count() 
    });

关于c# - 在 C# 中查找列表中的多个重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44931021/

相关文章:

c# - 只对一个对象设置属性

c# - 如何避免在布局页面中使用 "using System.Web.Optimization"

c# - 在 C# 中比较列表并返回匹配项

c# - 如何在 C# 中对具有原始顺序的列表进行排名

c# - C# 中的泛型列表和静态变量行为

C# - 如何在 IQueryable 对象中搜索 Where Like %

c# - 缓慢迁移公共(public)网站

c++ - 我应该使用什么类型的容器来存储我的 ObjectID 整数?

python - 二维列表的排列 (Python)

python - python 列表中的 Latex 表达式用于 matplotlib 中的标签