首页 > 解决方案 > 按属性将对象分组到字典

问题描述

我想Files按扩展分组。我的FileDto样子是这样的:

public class FileDto
{
    public string Extension { get; set; }

    public string Filename { get; set; }
}

我想做Dictionary(或任何其他集合)将我files的分组Extension(例如".txt"".doc")等。我开始编写一些代码:

// input.Files = IEnumerable<FileDto>

Dictionary<string, IEnumerable<FileDto>> dict = input.Files
    .GroupBy(x => x.Extension) // i want to Extension by my key (list of txts, list of docs etc)
    .ToDictionary(y => y.Key); // not working

foreach (var entry in dict)
{
    // do something with collection of files
}

我的问题是,如何按属性对对象列表进行分组?

标签: c#

解决方案


好吧,您可以传递第二个参数并将 IGrouping 转换为 enumerable

input.GroupBy(x => x.Extension).ToDictionary(y => y.Key, y => y.AsEnumerable());

推荐阅读