2013-02-26 61 views
2

我正在尋找一個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); 
    } 
} 
+1

好像你的示例代碼可能不會做你希望它... – 2013-02-26 23:17:30

+0

的inner.Id將是什麼獨一無二。而每個內心只能屬於一個外部。我已經正確地工作了,但我只是尋找更優雅的解決方案。 – 2013-02-26 23:19:33

+1

真的值得嗎?看起來你不需要懶惰的執行,或者其他任何linq特有的功能。 – 2013-02-26 23:20:04

回答

4

退房Enumerable.Join和Enumerable.ToDictionary。

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

你測試了嗎? – 2013-02-26 23:31:52

+0

你指的是導致'Dictionary >'的map的Type類型嗎?我想我可以在最後加上一個「選擇」。但這不是值得投票的。 – Sorax 2013-02-26 23:34:41

+0

不,我指的是比較'b.OuterId'('長')和'a'('外')。你的意思是'b.OuterId == a.Id'? – 2013-02-26 23:36:51

0

以下應工作(現在寫測試用例):

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); 
0
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);