var missing = from l1 in List1
join l2 in List2 on l1.Name equals l2.Name into merged
from missed in merged.DefaultIfEmpty()
select missed;
我可能是个十足的白痴,但我已经盯着这个看了一整天了,却无法明白。任何帮助,将不胜感激。
你所拥有的是功能性的Except,但您不想使用整个项目的相等性,而是想要执行Except使用选定的属性作为键。虽然您可以提供自定义IEqualityComparer to Except仅比较名称,编写比较器是相当容易出错的样板代码。我们可以编写一个方法来执行Except相当容易地在投影键上:
public static IEnumerable<TSource> ExceptBy<TSource, TKey>(
this IEnumerable<TSource> source,
IEnumerable<TSource> other,
Func<TSource, TKey> keySelector)
{
var set = new HashSet<TKey>(other.Select(keySelector));
foreach(var item in source)
if(set.Add(keySelector(item)))
yield return item;
}
这使用给定的键而不是自定义的相等比较器执行 except。
现在您的查询很简单:
var query = list1.ExceptBy(list2, dog => dog.name);