billb
billb

Reputation: 3619

Linq Return Filtered Children

I'm having a 'duh' moment where this seems like it should be straight forward, but I can't seem to get it right. I have a simple collection:

Category Name
   ---> List<Category>  (Children of this category)

I want the user to be able to filter based on Category.Name while maintaining the hierarchy. So for example.

My Category
  ---> Category.Name, "ABC"
  ---> Category.Name, "123"
  ---> Category.Name, "CDE"

If the user types C, the filter should return

My Category
  ---> Category.Name, "ABC"
  ---> Category.Name, "CDE"

My attempt thus far has been

var v = vm.CategoryList
        .Where(p => p.CategoryItems.Any(q => q.Name.Contains(SearchText)));

This will filter and give me back all Category Names that contain category items which match the filter, but I still get the entire child category list, unfiltered. What am I missing?

Upvotes: 1

Views: 941

Answers (1)

SLaks
SLaks

Reputation: 887453

You need to call Select and return a filtered child list, like this:

var v = vm.CategoryList
          .Select(p => new { p.CategoryName, CategoryItems = p.CategoryItems.Where(q => q.Name.Contains(SearchText)))
          .Where(p => p.CategoryItems.Any()));

Upvotes: 6

Related Questions