【发布时间】:2016-11-04 11:37:20
【问题描述】:
我有 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);
【问题讨论】:
-
你可以用 lambda 缩短它,我现在不能举个例子,对不起
-
你能解释一下你的最后一行应该做什么吗?它应该告诉你哪个字典匹配最多?
-
您的代码究竟是如何没有按预期工作的?
-
您可以将所有这些
foreach语句组合成一个其中只有每个if语句的语句,并且您可以循环遍历d的Keys。 -
@Rob 是的,我正在尝试获取与其匹配最多的字典,但我与一位朋友交谈,我发现了这个问题的问题。我正在计算字典中有多少键,但每个字典都有 1 或 0 个包含该二元组的键。例如;他在每个字典中只出现 1 次,所以每个 int 的值都是 1。
标签: c# dictionary foreach