[英]C# How to make a list of Dictionaries into array
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);
我可以使用
var r = Merge(r1,r2,r3);
and it will work fine. 它将正常工作。 r1,r2,r3 are dictionaries.
r1,r2,r3是字典。 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.
问题是我不知道我拥有的词典数量,它会波动,有时是3,有时是30或300。我的词典在列表中。 Actualy I have a list of a class.
实际上,我有一个班级的清单。 so somehow I have to make it work in a foreach loop?
所以我必须以某种方式使其在foreach循环中工作?
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
. 新函数merge采用
Class1
的IEnumerable并将其合并到Dictionary
。 It uses the Merge(IEnumerable<Dictionary<double, double>> dicts)
the is defined below: 它使用
Merge(IEnumerable<Dictionary<double, double>> dicts)
定义如下:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.