2

我正在寻找一个 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

4 回答 4

5
var map = inners
          .ToDictionary(a => a.Id, 
                        a => outers
                             .Where(b => b.Id == a.OuterId)
                             .Select(b => b.Id)
                             .First()
                        );
于 2013-02-26T23:22:35.920 回答
4

查看 Enumerable.Join 和 Enumerable.ToDictionary。

于 2013-02-26T23:21:52.143 回答
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);
于 2013-02-26T23:25:58.830 回答
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);
于 2013-02-26T23:26:31.873 回答