Adam Levitt
Adam Levitt

Reputation: 10476

Convert two lists to a dictionary

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

Answers (4)

Sorax
Sorax

Reputation: 2203

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

Upvotes: 5

System Down
System Down

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

Oscar Mederos
Oscar Mederos

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

Timothy Shields
Timothy Shields

Reputation: 79461

Check out Enumerable.Join and Enumerable.ToDictionary.

Upvotes: 4

Related Questions