循环遍历多个词典

时间:2016-11-04 11:37:20

标签: c# dictionary foreach

我有6本词典。我想比较其他每个字典,看看哪些字典包含哪些字符串。是否可以使用foreach循环?

static Dictionary<string, int> d = new Dictionary<string, int>();
static Dictionary<string, double> dNL = new Dictionary<string, double>();
static Dictionary<string, double> dDE = new Dictionary<string, double>();
static Dictionary<string, double> dFR = new Dictionary<string, double>();
static Dictionary<string, double> dSP = new Dictionary<string, double>();
static Dictionary<string, double> dEN = new Dictionary<string, double>();
static Dictionary<string, double> dIT = new Dictionary<string, double>();

foreach (var f in d)
{
    if (dNL.ContainsKey(f.Key))
    {
        //add to a numeric?
    }
    if (dDE.ContainsKey(f.Key))
    {
        //add to a numeric?
    }
}

这样的事情?

我目前拥有的(并且没有像预期的那样工作):

// need to find a better solution
foreach (var f in d)
{
    if (dNL.ContainsKey(f.Key))
    {
        dNLtotaal++;
    }
}
foreach (var f in d)
{
    if (dDE.ContainsKey(f.Key))
    {
        dDEtotaal++;
    }
}
foreach (var f in d)
{
    if (dFR.ContainsKey(f.Key))
    {
        dFRtotaal++;
    }
}
foreach (var f in d)
{
    if (dSP.ContainsKey(f.Key))
    {
        dSPtotaal++;
    }
}
foreach (var f in d)
{
    if (dEN.ContainsKey(f.Key))
    {
        dENtotaal++;
    }
}
foreach (var f in d)
{
    if (dIT.ContainsKey(f.Key))
    {
        dITtotaal++;
    }
}
// NEED A MUCH BETTER SOLUTION
List<int> totaleD = new List<int>();
totaleD.Add(dNLtotaal);
totaleD.Add(dDEtotaal);
totaleD.Add(dFRtotaal);
totaleD.Add(dSPtotaal);
totaleD.Add(dENtotaal);
totaleD.Add(dITtotaal);
int max = !totaleD.Any() ? -1 : totaleD.Select((value, index) => new { Value = value, Index = index }).Aggregate((a, b) => (a.Value > b.Value) ? a : b).Index;
var maxIndex = totaleD.IndexOf(totaleD.Max());
Console.WriteLine(maxIndex);

3 个答案:

答案 0 :(得分:3)

您可以这样做:

var items = d.Keys;
var dictionaries = new[] { dNL, dDE, dFR, dSP, dEN, dIT };
var result = dictionaries.Select((d, index) =>
    new {
        Index = index,
        Matches = items.Count(i => d.ContainsKey(i))
    })
    .OrderByDescending(i => i.Matches)
    .Select(i => i.Index)
    .FirstOrDefault();

它为您提供了匹配最多的词典的索引

答案 1 :(得分:0)

您可以使用lambda表达式来获得所需的结果。在下面的示例中,我尝试使用两个词典:

int dNLtotaal = 0;
Dictionary<string, double> dNL = new Dictionary<string, double>();
Dictionary<string, double> dDE = new Dictionary<string, double>();

dNL.Keys.Where(k => dDE.ContainsKey(k)).ToList().ForEach(k => dNLtotaal++);

希望有所帮助

答案 2 :(得分:0)

为什么不使用1个词典而不是6个?并保留一对[string,List [SomeObject]],其中SomeObject是类

class SomeObject
{
    public Enum Type;//dNL, dDE etc
    public double Value;
}