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

标签 c# .net linq

我有一组集合,其构建方式是“children”(possible_child) 集合中的每个对象至少应该有一个父集合 (possible_parent)。我想检测那些没有父对象的 child 。 例如,如果我找到一个没有给定国家、年份、季节和季节类型的 child ,至少应该有一个具有相同数据的父记录。

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

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();

有人可以提出更好的主意吗?

最佳答案

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

关于c# - 使用 LINQ 查找缺少父对象的子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33755954/

相关文章:

c# - 如何从另一个列表中删除列表中的字符串?

.net - 如何在 MSDN 中仅查看 .NET 类添加的属性/方法,而不是继承的属性/方法?

c# - 我可以称之为依赖注入(inject)吗?

c# - Parallel.ForEach 没有执行该方法

c# - 使用自定义条件和分隔符拆分字符串

c# - 使用参数中的字段名称对 IList 进行排序

c# - 如何从 Windows Phone 8.1 Silverlight 中的列表框中删除所选项目

c# - 许多读者,一个作者 - 是否有可能避免锁定?

c# - 计算 2 个数组的数量差

c# - 有条件地加入 LINQ