2013-02-26 84 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);