简体   繁体   English

使用LINQ从对象列表中获取不同的参数列表

[英]Using LINQ to get a distinct list of Parameters from a list of objects

So I have List of reports, and each report object has a ParameterCollection (which inherits CollectionBase ) which contains each Parameter in that collection. 所以我有报告列表,每个报告对象都有一个ParameterCollection (继承CollectionBase ),它包含该集合中的每个Parameter I would like to get the unique parameters across all reports. 我想在所有报告中获得独特的参数。

I've already got it working a longer (probably inefficient) way via looping through each report in list and then looping through each parameter in collection, adding to a temp list and then using the .Distinct() on that but I figured there was a better way with LINQ but I just can't quite get it. 我已经通过循环遍历列表中的每个报告,然后循环遍历集合中的每个参数,添加到临时列表然后使用.Distinct() ,我已经得到它工作更长(可能是低效)的方式但我认为有使用LINQ更好的方法,但我不能完全理解它。 Tried combinations of Select() and SelectMany() . 尝试了Select()SelectMany()

Any thoughts? 有什么想法吗? Thanks! 谢谢!

Orginal Code 原始代码

var reportParams = SelectedReports.ToDictionary(rpt => rpt.Name, rpt => rpt.Parameters); 
var uniqueParams = new Dictionary<string, Parameter>();

foreach (var collection in reportParams.Values)
{
    foreach (Parameter param in collection)
    {
        if (!uniqueParams.ContainsKey(param.Name))
            uniqueParams.Add(param.Name, param);
    }
}

var finalCollection = new ParameterCollection();

foreach (var param in uniqueParams.Values.Distinct())
{
    finalCollection.Add(param);
}

return finalCollection;
var uniqueParams = reports.SelectMany(report => report.Parameters).Distinct();

编辑:

var uniqueParams = reports.SelectMany(report => report.Parameters.Cast<Parameter>()).Distinct();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM