简体   繁体   English

使用 Linq c# 在集合中过滤集合

[英]Filtering Collection within a Collection using Linq c#

I have the following collection.我有以下收藏。 How do i get the list of toys containing one or more Category Name starting with "ABC".我如何获得包含一个或多个以“ABC”开头的类别名称的玩具列表。 The toys returned in the collection should only have Category with Name containg "ABC" and disregard other Category name NOT starting with "ABC".退回的玩具只能有名称包含“ABC”的类别,忽略其他名称不以“ABC”开头的类别。

So the example below will return a collection with one toy (name=teddy1) with only two Cartegoris ignoring Category starting with "XYZ"因此,下面的示例将返回一个包含一个玩具 (name=teddy1) 的集合,其中只有两个 Cartegoris 忽略以“XYZ”开头的类别

    var toys = new List<Toy>()
    {
        new Toy()
        {
            name = "teddy1",
            category = new List<Category>()
            {
                new Category()
                {
                    Name = "ABC xxx"
                },
                new Category()
                {
                    Name = "XYZ yyy"
                },
                new Category()
                {
                    Name = "ABC zzz"
                },
            }
        },
        new Toy()
        {
            name = "teddy2",
            category = new List<Category>()
            {
                new Category()
                {
                    Name = "AAA"
                }
            }
        }
    };

You need to filter the main array and then for every item you need to filter the categories list.您需要过滤主数组,然后为您需要过滤类别列表的每个项目。 You can achieve it like below:您可以像下面这样实现它:

var targetCategoryName = "ABC";

var targetList = tosy
    .Where(r=> r.Categories.Any(q=> q.Name.StartsWith(targetCategoryName)))
    .Select(r=> new Toy()
    {
        name = r.Name,
        Categories = r.Categories
            .Where(q => q.Name.StartsWith(targetCategoryName))
            .ToList()
    })
    .ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM