Reputation: 10476
I'm looking for a LINQ function that could replace my two loops here to produce a similar result:
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);
}
}
Upvotes: 2
Views: 2166
Reputation: 2203
var map = inners
.ToDictionary(a => a.Id,
a => outers
.Where(b => b.Id == a.OuterId)
.Select(b => b.Id)
.First()
);
Upvotes: 5
Reputation: 6270
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);
Upvotes: 0
Reputation: 29843
The following should work (writing test cases now):
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);
Upvotes: 0