简体   繁体   中英

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. 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. Tried combinations of Select() and 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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