2012-07-25 49 views
4

我有两个共享两个公共属性Id和Information的类。将两个类合并到使用LINQ的字典中

public class Foo 
{ 
    public Guid Id { get; set; } 

    public string Information { get; set; } 

    ... 
} 
public class Bar 
{ 
    public Guid Id { get; set; } 

    public string Information { get; set; } 

    ... 
} 

使用LINQ,我怎么能采取的Foo对象填充的列表和酒吧对象填充的列表:

var list1 = new List<Foo>(); 
var list2 = new List<Bar>(); 

合并 Id和各信息到一个单一的词典:

var finalList = new Dictionary<Guid, string>(); 

在此先感谢您。

+0

你想有,如果有发生什么事做两个具有相同ID但信息不同的项目? – 2012-07-25 17:46:09

+0

@ErikPhilips这种可能性不会发生,所以它不是我需要处理的。 – Jonathan 2012-07-25 17:46:54

+0

检查这里的解决方案:http://stackoverflow.com/questions/4038978/map-two-lists-into-a-dictionary-in-c-sharp – 2012-07-25 17:48:23

回答

8

听起来像是你可以这样做:

// Project both lists (lazily) to a common anonymous type 
var anon1 = list1.Select(foo => new { foo.Id, foo.Information }); 
var anon2 = list2.Select(bar => new { bar.Id, bar.Information }); 

var map = anon1.Concat(anon2).ToDictionary(x => x.Id, x => x.Information); 

(你可以做到这一切在一个声明,但我认为这是更清楚的方式)

+0

一如既往的Jon,Jon。谢谢。 – Jonathan 2012-07-26 23:51:32

0
var finalList = list1.ToDictionary(x => x.Id, y => y.Information) 
      .Union(list2.ToDictionary(x => x.Id, y => y.Information)) 
         .ToDictionary(x => x.Key, y => y.Value); 

确保ID是唯一的。如果不是,它们将被第一个字典覆盖。

编辑:添加.ToDictionary(x => x.Key,y => y.Value);

+2

这不会导致字典... – 2012-07-25 17:50:11

+0

感谢乔恩,现在应该工作。 – 2012-07-25 18:03:30

+2

是的,它会工作 - 但它似乎有点浪费,国际海事组织。为什么要构建三个字典*和*时,只需连接并使用单个ToDictionary调用,就可以通过集合操作进行操作? – 2012-07-25 18:06:44