tags:

views:

81

answers:

1

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?

+3  A: 

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()));
SLaks
I think he needs a solution that will search down the hierarchy N levels, e.g. it has to be recursive
Alex Black
Some syntax errors, but I got the gist and this is what I was looking for. Thank you. Proper syntax is: var v = vm.CategoryList.Select(p => new { p.CategoryName, Items = p.CategoryItems.Where(q => q.Name.Contains(SearchText)).Where(a => a.CategoryName.Any()) } )
billb
You want to write `.Where(a => a.CategoryItems.Any())` (not `Name`)
SLaks