将两个列表转换为词典

本文关键字:转换 列表 两个 | 更新日期: 2023-09-27 18:01:12

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

将两个列表转换为词典

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

查看Enumerable.Join和Enumerable.ToDictionary.

以下应该可以工作(现在编写测试用例(:

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);
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);
相关文章: