【问题标题】:LINQ - Find all records where all items in a given list are contained in an icollectionLINQ - 查找给定列表中的所有项目都包含在一个集合中的所有记录
【发布时间】:2019-03-28 20:06:09
【问题描述】:

我有一个过滤器列表,我想用它来查询一个表,其中返回的项目包含所有值而不仅仅是一个。

该表称为组织,其中包含该组织的目标年龄组列表。

public class Organisation
{
public int OrganisationID { get; set; }
public string OrgName { get; set; }
public ICollection<OrgAgeGroup> AgeGroupCollection { get; set; }
}

OrgAgeGroup 类在下面

public class OrgAgeGroup
    {
        public int OrgAgeGroupID { get; set; }
        public int OrganisationID { get; set; }
        public int AgeGroupID { get; set; }
    }

最后从复选框中选择的值存储在一个 int 列表中:

List<int> selectedAges 

我正在使用以下代码来选择包含任何 selectedAges 的所有组织:

IQueryable<Organisation> orglist = GetAllOrgs();

 orglist = orglist.Where(o => o.AgeGroupCollection.Any(l => selectedAges.Contains(l.AgeGroupID)));

但我不知道如何获取包含所有选定年龄的所有组织。将 Any 更改为 All 似乎对搜索没有影响。有什么想法吗?

【问题讨论】:

    标签: c# list linq collections


    【解决方案1】:

    下面的查询应该会给你你想要的。

    orglist = orglist.Where(
        o => selectedAges.All(
            s => o.AgeGroupCollection
                .Select(l => l.AgeGroupID)
                .Contains(s)));
    

    您想要组织o,其中所有selectedAges s 都包含在oAgeGroupCollectionAgeGroupIds 的集合中。

    【讨论】:

      猜你喜欢
      • 2018-06-18
      • 2013-05-15
      • 1970-01-01
      • 2014-06-27
      • 2017-06-14
      • 1970-01-01
      • 2021-10-26
      • 2012-07-10
      相关资源
      最近更新 更多