本文介绍了使用LINQ仅基于单个对象属性来获取两个对象列表之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

狗类具有两个属性(名称和颜色)

the dog class has two properties (name and color)

假设我有两个IEnumerable列表:

Let's say I have two IEnumerable lists:

List1 [{name="Sam", color="Fawn"}, {name="Mary", color=""}, {name="Bob", color=""}]
List2 [{name="Mary", color="Black"},{name="Bob", color="Yellow"}]

我想获取只名称不同的狗对象列表

I want to get a list of dog objects that differ ONLY in name

所以我的退货清单看起来像

so my return list would look like

ListReturn: [{name="Sam", color="Fawn"}]

有道理吗?

我想用linq做到这一点.这是我尝试过的方法,但是没有用有帮助吗?

I want to do this with linq. This is what I've tried... and it's not workingany help?

  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;

我可能是个傻瓜,但我整天盯着它看,无法理解.任何帮助将不胜感激.

I may be a complete moron, but I've stared at this all day and can't get it. any help would be appreciated.

推荐答案

从功能上讲,您拥有的是Except,但您不想使用整个项目的相等性,而是希望使用选定的属性作为钥匙.虽然可以为Except提供仅用于比较名称的自定义IEqualityComparer,但是编写比较器是相当容易出错的样板代码.我们可以编写一种相当容易地在投影键上执行Except的方法:

What you have is functionally Except, but instead of using equality of the whole item, you want to perform the Except using a selected property as the key. While you could provide a custom IEqualityComparer to Except that only compared names, writing that comparer is a fair bit of error prone boilerplate code. We can write a method that performs an Except on a projected key fairly easily:

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;
}

这将执行除使用给定键而不是自定义相等比较器的操作.

This performs an except using the given key, instead of a custom equality comparer.

现在您的查询很简单:

var query = list1.ExceptBy(list2, dog => dog.name);

这篇关于使用LINQ仅基于单个对象属性来获取两个对象列表之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:08