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

时间:2017-07-05 15:58:02

标签: c# 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
    }

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

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

3 个答案:

答案 0 :(得分:4)

有些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() 
    });

答案 1 :(得分:3)

var totalNumber = document.getElementById("total");
totalNumber.textContent = "";
document.getElementById("numbers").addEventListener('click', function(e){
    totalNumber.textContent += e.target.innerText;
})

答案 2 :(得分:1)

  var grp = cars.GroupBy(g => new { g.brand, g.color }).Select(n => new {
                brand = n.Key.brand,
                color = n.Key.color,
                count = n.Count()

            });