【问题标题】:Extract a dictionary out of a list<T> using LINQ使用 LINQ 从列表<T> 中提取字典
【发布时间】:2016-06-11 22:09:59
【问题描述】:

我有Pencil 对象List&lt;Pencil&gt; pencils 的列表如下:

public class Pencil
{
    public Pencil(int quantity, Color color)
    {
        Quantity = quantity;
        Color = color;
    }

    public int Quantity { get; set; }
    public Color Color { get; set; }
}

var pencils = new List<Pencil>
{
    new Pencil(3, Blue),
    new Pencil(2, Red),
    new Pencil(5, Blue),
};

我想要做的是能够使用 LINQ 提取这样的字典:

Dictionary<Color, int> ColorAndQuantities;

【问题讨论】:

  • 好的,你想要一些东西,但是你试图得到什么?还是就像“我懒得看文档,帮我做吧”之类的问题?
  • 如果你不能用 linq 来做,你可以用经典的循环来做,不是吗?展示你的努力......
  • @Eser 为什么这么生气?

标签: c# linq list dictionary group-by


【解决方案1】:

您应该按颜色分组,然后使用ToDictionary 创建一个字典,其中包含每种颜色作为键和该颜色的数量之和作为值,如下所示:

var result =
    pencils
    .GroupBy(x => x.Color)
    .ToDictionary(g => g.Key, g => g.Sum(x => x.Quantity));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多