如何使用LINQ从多个对象中提取特性

本文关键字:提取 对象 何使用 LINQ | 更新日期: 2023-09-27 18:00:07

我经常发现自己在做下面的事情,从对象列表中提取属性,只是为了创建一个聚合列表。LINQ将如何表达这一点?

var totalErrors =
    new Dictionary<string, string>();
foreach (var res in results)
{
    foreach (var err in res.Errors)
    {
        totalErrors
            .Add(err.Key, err.Value);
    }
}
return totalErrors;

如何使用LINQ从多个对象中提取特性

您可以使用SelectManyToDictionary方法:

var result = results
     .SelectMany(x => x.Errors) // get all Errors in one sequence
     .ToDictionary(x => x.Key, x => x.Value); // create new dictionary based on this Enumerable

CCD_ 3将序列的每个元素投影到CCD_。并且ToDictionary()根据指定的密钥选择器功能从IEnumerable<T>创建Dictionary<TKey, TValue>

您可以使用SelectMany在两个级别上进行聚合,如下所示:

var totalErrors = results
    .SelectMany(r => r.Errors)
    .ToDictionary(e => e.Key, e => e.Value);

SelectMany将集合集合"展平"为一个级别,此时可以将ToDictionary应用于展平的列表。

您可以使用SelectMany:

var allErrors = Results.SelectMany( res=>res.Errors );
//foreach( var error in allErrors )...
var dictionary = allErrors.ToDictionary( x=>x.Key, x=> x.Value );