【问题标题】:C# Intersection of 2 collections based on certain properties基于某些属性的 2 个集合的 C# 交集
【发布时间】:2014-11-12 01:12:40
【问题描述】:

我有一个WebItem 对象定义为

public class WebItem
{
    public string Title;
    public string Url;
    public string RandomProperty1;
    public string RandomProperty2;
    public string RandomProperty3;
}

我有两个Lists 的WebItem 对象,我正在尝试找出List 1 中是否有List 2 中的对象。但问题是,如果至少 TitleUrl 相同,我会认为它匹配。我不太关心其他属性的值是什么。

例子:

List 1
   1: Title="Dog", Url="/dog.aspx", RandomProperty1="Yorkshire"
   2: Title="Cat", Url="/cat.aspx", RandomProperty1="Persian", RandomProperty2="Grey"
   3: Title="Rat", Url="/rat.aspx"

List 2
   1: Title="Dog", Url="/dog.aspx", RandomProperty1="Pitbull"
   2: Title="Cat", Url="/kitten.aspx", RandomProperty1="Persian", RandomProperty2="Grey"
   3: Title="Bird", Url="/bird.aspx", RandomProperty1="Parrot"

在这种情况下,唯一的“匹配”将是“狗”,因为 TitleUrl 相同。

我将如何在 Linq 中执行此操作?我考虑过使用.Intersect,但我不确定有关属性的条件。

【问题讨论】:

    标签: c# linq .net-3.5


    【解决方案1】:

    您可以提供自己的 GetHashCodeEquals 覆盖,如果您确实打算在所有情况下,如果两个属性相等,则两个项目相等。如果不是这种情况,并且您只希望平等以这种方式工作以实现这一操作,请使用 linq Intersect 但使用 different overload 并提供您自己的 IEqualityComparer<T>

    【讨论】:

    • 哦,没有意识到Intersect 可以承受过载。谢谢!
    【解决方案2】:

    只需为您的类实现 IEqualityComparer<T>(例如 GetHashcode 和 Equals),然后使用 Intersect。

    实现 Equals 方法的一个例子是:

    public bool Equals(WebItem x, WebItem y)
    {
        return x.Title == y.Title && x.Url == y.Url;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      相关资源
      最近更新 更多