【问题标题】:Filter list of objects, where nested collection matches an array过滤对象列表,其中嵌套集合匹配数组
【发布时间】:2018-11-22 18:21:20
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c# arrays linq icollection


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的快速解决方案!
    猜你喜欢
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2020-12-02
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多