【问题标题】:Compare lists and get unique elements比较列表并获得独特的元素
【发布时间】:2014-03-17 07:45:28
【问题描述】:

我有一个名为 Parent 的对象和一个名为 Child 的对象列表。 Parent 对象还有一个 Child 的列表。

public class Parent 
{
   public Parent() 
   {
      Children = new List<Child>();
   }

   public string Name { get; set; }
   public IList<Child> Children { get; set; }
}

public class Child
{
   public string Name { get; set; }
   ....
}

现在我想从列表中获取那些不存在于父母的孩子列表中的孩子。

如何使用 linq/lambda 表达式实现这一点?

我尝试过的代码没有成功:

Parent parent = GetParent();
List<Child> children = GetChildren();

var notExistingChildren = children.Where(child => !parent.Children.Any(ch => ch.Name == child.Name)).ToList();

children 有 1 个元素在 parent.Children 中不存在,但此表达式没有获取该元素并将其分配给 notExistingChildren。

【问题讨论】:

  • 那么,您目前的方法到底有什么问题?你能提供(不)匹配的名字吗?

标签: c#


【解决方案1】:

您的方法不是很有效,因为您正在为children 集合中的每个孩子枚举父母孩子。如果名称的大小写不同,您也可能会遇到问题 - 例如"Bob""bob" 在 C# 中是不同的字符串。但是如果名称相同,您的方法应该有效:

var notExistingChildren = 
    children.Where(c => !parent.Children.Any(pc => pc.Name == c.Name))
            .ToList();

更高效且易于阅读的方法是为Child 类实现EqualsGetHashCode 方法(或为Child 类创建自定义IEqualityComparer)。在这种情况下,您将能够使用执行设置操作的Enumerable.Except

var notExistingChildren = children.Except(parent.Children).ToList();

如果可以使用子名作为标识,则可以通过以下方式覆盖EqualsGetHashCode

public override bool Equals(object obj)
{
    Child other = obj as Child;
    if (other == null)
        return false;

    return other.Name == Name;
}

public override int GetHashCode()
{
    return Name.GetHashCode();
}

顺便说一句,我使用以下示例数据尝试了您的代码,它工作正常 - Joe 作为不存在的孩子返回。

List<Child> children = new List<Child>
{
    new Child { Name = "Bob" },
    new Child { Name = "Joe" }
};

Parent parent = new Parent
{
    Children = new List<Child> { new Child { Name = "Bob" } }
};

如果您在结果中没有看到某些孩子,则说明父母的孩子集合中存在同名的孩子。没有别的办法。

【讨论】:

  • 对不起,我的错。我现在已经检查了所有元素(大约 150 个)并找到了匹配项。但是感谢您提供更具可读性的替代方案。我会用这个代替。
【解决方案2】:

这个表达对我来说很好。使用 ch.Name.ToLower() == child.Name.ToLower() 进行比较,因为您的列表可能有不同的字符大小写

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
  • 2023-04-03
  • 2015-09-30
相关资源
最近更新 更多