将两个列表转换为字典

时间:2013-02-26 23:14:17

标签: c# linq

我正在寻找可以替换我的两个循环的LINQ函数,以产生类似的结果:

public class Outer {
    public long Id { get; set; }
}

public class Inner {
    public long Id { get; set; }
    public long OuterId { get; set; }
}

var outers = new List<Outer>();
var inners = new List<Inner>();
// add some of each object type to the two lists

// I'd like to replace this code with a LINQ-style approach
var map = new Dictionary<long, long>();
foreach (Outer outer in outers) {
    foreach (Inner inner in inners.Where(m => m.OuterId == outer.Id)) {
        map.Add(inner.Id, outer.Id);
    }
}

4 个答案:

答案 0 :(得分:5)

var map = inners
          .ToDictionary(a => a.Id, 
                        a => outers
                             .Where(b => b.Id == a.OuterId)
                             .Select(b => b.Id)
                             .First()
                        );

答案 1 :(得分:4)

查看Enumerable.Join和Enumerable.ToDictionary。

答案 2 :(得分:0)

以下内容应该有效(现在编写测试用例):

var map = inners.Join(outers, x => x.OuterId, x => x.Id, (inner, outter) => new
    {
        InnerId = inner.Id,
        OuterId = outter.Id
    }).ToDictionary(x => x.InnerId, x => x.OuterId);

答案 3 :(得分:0)

var dict = (for outer in outers
            join inner in inners
            on outer.Id equals inner.OuterId
            select new KeyValuePair<long,long>(inner.Id, outer.Id)).ToDictionary(k => k.Key, v => v.Value);