I have 2 lists that I need to consolidate. List 1 has only the dates, and List 2 may have the time element as well:
var List1 = new[] {
new ListType{ val = new DateTime(2012, 1, 1)},
new ListType{ val = new DateTime(2012, 1, 2)}
};
List2 = new[] { new ListType{ val = new DateTime(2012, 1, 1, 5, 0, 0)} };
FinalList = new[] {
new ListType{ val = new DateTime(2012, 1, 1, 5, 0, 0)},
new ListType{ val = new DateTime(2012, 1, 2)}
};
The way I’m going about this is:
foreach (var l in List1) {
var match = List2.FirstOrDefault(q => q.val.Date == l.val);
if (match == null) continue;
l.val = match.val;
}
Is there a better way than iterating through List1, using FirstOrDefault and then reassigning the val? It works, so this is just more a curiosity if Linq has a more elegant way (i.e. I am missing something obvious).
Thanks
You can use
Enumerable.Unionwith a customIEqualityComparer<ListType>:and then …