Reputation: 26919
I have two lists of this class for example 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
always has equal or more items in it than List2
. List2 is pretty much a subset of List1
The primary key is that 'id
' property.
I want to create a third list out of these two lists such that it will have all the items of List1
BUT for the items that have the same id in both lists, use property values from List1
EXCEPT for selected and "sortOrder" property, use List2 for that.
I can't think of a way to start approaching this. So I need some help.
Upvotes: 0
Views: 759
Reputation: 14477
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();
Upvotes: 2