簡體   English   中英

將兩個列表轉換為字典

[英]Convert two lists to a dictionary

我正在尋找一個可以替換我的兩個循環的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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM