我有两个此类的列表,例如List1
,List2
public class SearchCriteriaOption
{
public string id { get; set; }
public string name { get; set; }
public string description { get; set; }
public bool selected { get; set; }
public bool required { get; set; }
public int sortOrder { get; set; }
}
List1
总是包含与List2
相同或更多的项目。 List2几乎是List1的子集
主键是' id
'属性。
我想在这两个列表中创建第三个列表,以便它们具有List1
但的所有项目,以便在两者中具有相同ID的项目列表,使用List1
EXCEPT 的属性值,用于选择和" sortOrder "属性,使用 List2 。
我无法想出一种开始接近这一点的方法。所以我需要一些帮助。
答案 0 :(得分:2)
var List3 = List1
.GroupJoin(List2,
o1 => o1.id, o2 => o2.id,
(option1, option2) => new { option1, option2 })
.SelectMany(
x => x.option2.DefaultIfEmpty(),
(x, option2) => new SearchCriteriaOption
{
// use most properties from list1
id = x.option1.id,
description = x.option1.description,
name = x.option1.name,
required = x.option1.required,
// using list2 for selected and sortOrder if available
// (if you cant use C# 6 syntax, use the next 2 lines)
//selected = option2 != null ? option2.selected : x.option1.selected,
//sortOrder = option2 != null ? option2.sortOrder : x.option1.sortOrder,
selected = option2?.selected ?? x.option1.selected,
sortOrder = option2?.sortOrder ?? x.option1.sortOrder,
})
.ToList();