I have a method which accept params of Dictionary
static IDictionary<double, double> Merge(params Dictionary<double, double>[] dicts)
{
return dicts.SelectMany(p => p).ToLookup(p => p.Key, p => p.Value)
.ToDictionary(p => p.Key, p => p.Max());
}
I can use var r = Merge(r1,r2,r3);
and it will work fine. r1,r2,r3 are dictionaries. The problem is I don't know the number of Dictionaries I have, it fluctuates , sometimes 3, sometimes 30, or 300. I have the dictionaries in a list. Actualy I have a list of a class. so somehow I have to make it work in a foreach loop?
List<Class1> c = new List<Class1>();
class Class1
{
public Dictionary<Double, Double> r1 = new Dictionary<Double, Double>();
}
您有一个接受字典数组的方法,因此只需要将列表变成数组即可。
var result = Merge(listOfDictionaries.ToArray());
after the original question was edited, now a update that should fix your problem. The new function merge takes an IEnumerable of Class1
and merges it to a Dictionary
. It uses the Merge(IEnumerable<Dictionary<double, double>> dicts)
the is defined below:
static Dictionary<Double, Double> Merge(IEnumerable<Class1> classes)
{
return Merge(classes.Select(c => c.r1));
}
Original Answer :
a small change in your parameter type definition should do it
static IDictionary<double, double> Merge(IEnumerable<Dictionary<double, double>> dicts)
{
return dicts.SelectMany(p => p)
.ToLookup(p => p.Key, p => p.Value)
.ToDictionary(p => p.Key, p => p.Max());
}
now you can just pass a list of dictionaries
EDIT If you want to use both variations, you can do this like this
static IDictionary<double, double> Merge(params Dictionary<double, double>[] dicts)
{
return Merge((IEnumerable<Dictionary<double, double>>)dicts);
}
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.