使用LINQ查找缺少父对象的子对象

本文关键字:对象 LINQ 查找 使用 | 更新日期: 2023-09-27 18:22:16

我构建了一组集合,这样"children"(possible_child)集合中的每个对象都应该至少有一个父集合(parent collection)。我想检测那些没有父对象的孩子。例如,如果我发现一个孩子的国家、年份、季节和季节类型都没有,那么至少应该有一个具有相同数据的父母记录。

我写了以下查询,现在我发现它是错误的。

var childrenMissingParents = (from cl in possible_child
join pr in possible_parent on new
 {
   p1=cl.Country,
   p2=cl.Year,
   p3=cl.Season,
   p4=cl.SeasonType
  }
    equals
  new
  {
    p1=pr.Country,
    p2=pr.Year,
    p3=pr.Season,
    p4=pr.SeasonType
  }
into opr from spr in opr.DefaultIfEmpty()
where spr == null select cr).ToList();

有人能提出一个更好的主意吗?

使用LINQ查找缺少父对象的子对象

var childrenMissingParents = possible_child.Where(
    c => !possible_parent.Any(
        p => p.Country == c.Country
     && p.Year == c.Year
     && p.Season == c.Season
     && p.SeasonType == c.SeasonType));

如果我理解正确,以下内容可以满足您的要求:

var orphanedItems = possible_child
    .Where(item => !possible_parent.Any(p =>
        (p.Year == item.Year) &&
        (p.Country == item.Country) &&
        (p.Season== item.Season) &&
        (p.SeasonType == item.SeasonType)));

您可以使用Where和Any来实现您的目标。

var childrenWithoutParent = possible_child.Where(child => !possible_parent.Any(p =>
                                                                   (p.Year == child.Year) &&
                                                                   (p.Country == child.Country) &&
                                                                   (p.Season == child.Season) &&
                                                                   (p.SeasonType == child.SeasonType)));

然而,你可以提高对代码的阅读能力,你可以在你的孩子身上有一个方法来与父母进行比较:

public class Child
    {
        ....
        public bool IsEqualsTo(Parent parent)
        {
            return (this.Year == parent.Year) &&
                   (this.Country == parent.Country) &&
                   (this.Season == parent.Season) &&
                   (this.SeasonType == parent.SeasonType)));
        }
    }

这可以提高查询的可读性。

  var childrenWithoutParent = possible_child
                                    .Where(child => !possible_parent.Any(p => child.IsEqualsTo(p));