我有两个共享两个公共(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 和信息合并到一个字典中:
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/