1

我不确定是否有更有效的方法来做我正在使用 LINQ 做的事情......我有两个枚举:

enumA(string): { "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 并以这种方式创建字典对我来说似乎很糟糕。

4

4 回答 4

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);
于 2012-11-16T19:46:46.993 回答
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);
于 2012-11-16T19:55:03.510 回答
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;
    });

这将保留最后一个匹配值。

于 2012-11-16T19:56:27.087 回答
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 是为了消除 enumB 中可能的重复。

如果 enumB 重复项不存在,您可以将其简化为

var dict = enumA.Join(enumB, a => a, b => b, (a, b) => new {a, b})
                .ToDictionary(x => x.a, x => x.b);
于 2012-11-16T20:02:01.060 回答