c# - 按属性将对象分组到字典
问题描述
我想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
}
我的问题是,如何按属性对对象列表进行分组?
解决方案
好吧,您可以传递第二个参数并将 IGrouping 转换为 enumerable
input.GroupBy(x => x.Extension).ToDictionary(y => y.Key, y => y.AsEnumerable());
推荐阅读
- python - While executing the below script I get the error "'chromedriver' executable needs to be in PATH"
- css - How to select in css 1st 4th 5th or 2nd 3rd 6th element
- node.js - 尝试在节点中呈现 JSX 时出现意外令牌
- react-native - TouchableNativeFeedback onLongPress radius not affected
- c# - How to fill the rectangle with some colors, using gradient but only as a tool(without visible gradient)?
- angular - Angular 6 Reactive Form:如何修复 TypeError:formDirective.resetForm() 不是函数
- xamarin.forms - FFImageloading - 检查图像是否存在于缓存中?
- salesforce - 在 Salesforce 相关内容(如联系人)中设置自定义字段(或)查找对象的样式
- python - 如何使用 cython 多次有效地组装刚度矩阵
- paypal - 使用 Phonegap 应用程序中的 REST API 的 Paypal 定期付款