筛选对象列表,其中嵌套集合与数组匹配

Filter list of objects, where nested collection matches an array

我有一个对象列表 (items),我想根据嵌套集合的值(对象 GenericItem 中的 Features)对其进行过滤。作为过滤器的基础,我有一个 int 数组 (filter)。我的 objective 是在 items 中找到所有对象,其中 Features 集合包括 至少 filter 数组中的所有值

根据在 Whosebug 上提供给其他人的许多解决方案,我编写了以下内容。我遇到的问题是,在我的 Linq 查询(以及我尝试过的许多变体)中,我总是最终得到 items 中的所有对象,其中所有 Features 都包含在 filter 中。我知道我的 lambda 表达式是 "in the wrong order",但是因为我想得到一个 GenericItem 的列表,所以我似乎无法弄清楚如何编写我的表达式。

我应该如何编写 Linq 表达式以获得预期的结果?

所以在下面,当我过滤 [2, 3] 的数组时,我的 objective 是让 result 持有 "Item A" 和 "Item B"(两者至少具有特征 2 和 3)。相反,我得到 "Item B" 和 "Item C" 的 result,因为 Featuresall 包含在 filter 数组中.

public class GenericItem {
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Feature> Features { get; set; }
}

public class Feature {
    public int Id { get; set; }
}

static void Main (string[] args) {

    var items = new List<GenericItem>();
    items.Add(new GenericItem() {
        Id = 1,
        Name = "Item A",
        Features = new Collection<Feature>() { 
            new Feature() {Id = 1},      
            new Feature() {Id = 2},      
            new Feature() {Id = 3}
        }      
    });
    items.Add(new GenericItem() {
        Id = 2,
        Name = "Item B",
        Features = new Collection<Feature>() {     
            new Feature() {Id = 2},      
            new Feature() {Id = 3}
        }      
    });
    items.Add(new GenericItem() {
        Id = 3,
        Name = "Item C",
        Features = new Collection<Feature>() {    
            new Feature() {Id = 3}
        }
    });

    int[] filter = new int[] {2, 3};

    var resultAll = items.Where(i => i.Features.All(f => filter.Contains(f.Id)));

    foreach (GenericItem I in resultAll)
        System.Console.WriteLine(I.Name);
}

All 应用到 filter 集合而不是 i.Features:

var resultAll = items.Where(i => filter.All(x => i.Features.Any(f => x == f.Id)));