4

我有两个类,它们共享两个共同属性,Id 和 Information。

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 对象的填充列表和 Bar 对象的填充列表:

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

并将每个的 Id 和 Information合并到一个字典中:

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

先感谢您。

4

2 回答 2

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

(你可以在一个语句中完成所有这些,但我认为这样更清楚。)

于 2012-07-25T17:49:11.520 回答
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);

于 2012-07-25T17:48:26.463 回答