我有两个类,它们共享两个公共(public)属性,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>();
先感谢您。
最佳答案
听起来你可以这样做:
// 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);
(你可以在一个声明中完成所有这些,但我认为这样更清楚。)
关于c# - 使用 LINQ 将两个类合并到一个字典中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11655548/