我不确定是否有更有效的方法来做我正在使用LINQ做的事情...我有两个枚举:
enumA(字符串):{ "Andy", "Bill", "Charlie", "Doug" }
enumB(foo):{ "Doug", "Edward", "George", "Bill" }
(注意,enumB实际上包含对象)
var dictionary = new Dictionary<string,
foreach (var a in enumA)
{
var b = enumB.SingleOrDefault(x => String.Equals(x.ToString(), a));
if (b != null)
dictionary[a] = b;
}
当我确定可能有更“正确”的方式使用LINQ创建字典时,我一遍又一遍地枚举enumB并且以这种方式创建字典似乎很难。
答案 0 :(得分:3)
您可以使用
高效地完成join
和
ToDictionairy
之后打电话。
var listA = "abcd";
var listB = "cdef";
var tuples = from charFromA in listA
join charFromB in listB
on charFromA.ToString() equals charFromB.ToString() // instead of ToString(), do something complex
select new { A = charFromA, B = charFromB };
var dictionairy = tuples.ToDictionary(keySelector: t => t.A,elementSelector: t => t.B);
答案 1 :(得分:1)
var query = from b in enumB.Where(x => x != null)
join a in enumA on b.ToString() equals a
select new { a, b };
var dictionary = query.ToDictionary(x => x.a, x => x.b);
或者使用流畅的API:
var dictionary = enumB.Where(b => b != null)
.Join(enumA,
b => b.ToString(),
a => a,
(b, a) => new { a, b })
.ToDictionary(x => x.a, x => x.b);
答案 2 :(得分:0)
var dictionary = enumA
.Join(enumB, a => a, b => b.ToString(), (a, b) => new { A = a, B = b })
.ToDictionary(i => i.A, i => i.B);
如果有任何重复键,这将抛出异常,因此您可以使用:
var dictionary = enumA
.Join(enumB, a => a, b => b.ToString(), (a, b) => new { A = a, B = b })
.Aggregate(new Dictionary<string, Foo>(), (dict, i) => {
dict[i.A] = i.B;
return dict;
});
将保留最后一个匹配值。
答案 3 :(得分:0)
var dict = enumA.Join(enumB, a => a, b => b, (a, b) => new {a, b})
.GroupBy(x => x.a)
.ToDictionary(x => x.Key, x => x.First());
GroupBy是为了消除枚举中可能的重复。
如果枚举重复项不存在,您可以将其简化为
var dict = enumA.Join(enumB, a => a, b => b, (a, b) => new {a, b})
.ToDictionary(x => x.a, x => x.b);