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

时间:2018-11-22 18:21:21

标签: c# arrays linq icollection

我有一个对象列表(items),我希望以此为基础过滤嵌套集合(对象Features中的GenericItem)的值。作为过滤器的基础,我有一个int(filter)数组。我的目标是要在items集合中找到所有对象,其中Features集合至少包含filter数组中的所有值。

在Stackoverflow上提供给他人的许多解决方案之后,我编写了以下内容。我遇到的问题是,在我的Linq查询(以及我尝试过的许多变体)中,我总是最终在items中获得所有对象,而所有Features都包含在filter中。我知道我的lambda表达式“顺序错误”,但是因为我想以GenericItem结尾,所以我似乎不知道该怎么写表达式。

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

因此在下面,当我过滤[2, 3]的数组时,我的目标是让result持有“ Item A”和“ Item B”(至少具有功能2和3) 。相反,我得到了“项目B”和“项目C”的result,因为它们的Features all 全部包含在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);
}

1 个答案:

答案 0 :(得分:1)

All应用于filter集合,而不是i.Features

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