我正在寻找一个可以替换我的两个循环的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);
}
}
Run Code Online (Sandbox Code Playgroud)
var map = inners
.ToDictionary(a => a.Id,
a => outers
.Where(b => b.Id == a.OuterId)
.Select(b => b.Id)
.First()
);
Run Code Online (Sandbox Code Playgroud)