简体   繁体   中英

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". The toys returned in the collection should only have Category with Name containg "ABC" and disregard other Category name NOT starting with "ABC".

So the example below will return a collection with one toy (name=teddy1) with only two Cartegoris ignoring Category starting with "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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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