O'Neil Tomlinson
O'Neil Tomlinson

Reputation: 888

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"
                }
            }
        }
    };

Upvotes: 0

Views: 73

Answers (1)

Eldar
Eldar

Reputation: 10790

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();

Upvotes: 1

Related Questions