Reputation: 21
I have a List of Elements. I need to get all the elements with a filter on each attribute where Category name is "XYZ".
The follow query definitely does a filter on attributes to select the attributes with category name "XYZ", but I want the element details of these filtered attributes as well.
var filteredAttributes = attributes.Where(at => at.Categories.Any(ca => ca.Name == "XYZ")).Any()).ToList();
But if I do the same filter on elements, I get all elements without a filter on attributes. Is it possible to create a one-line query to filter on elements to grab the necessary attributes?
This is the LINQ query I tried which fails:
var filteredElements = elements.Where(el => el.attributes.Where(at => at.Categories.Any(ca => ca.Name == "Alarm")).Any()).ToList();
Here are the classes defined:
public class Element
{
public string Name { get; set; }
public string ID { get; set; }
public Boolean HasChildren { get; set; }
public List<Attribute> Attributes { get; set; }
}
public class Attribute
{
public string Name { get; set; }
public string Description { get; set; }
public string Value { get; set; }
public string WebID { get; set; }
public List<Category> Categories { get; set; }
}
public class Category
{
public string Name { get; set; }
public string Description { get; set; }
}
Upvotes: 0
Views: 88
Reputation: 32445
Just put your first query inside Where
of elements
I think it will be enough to use Any
on attributes with inner Any
on categories
var filteredElements =
elements.Where(el =>
{
return el.attributes.Any(at => at.Categories.Any(ca => ca.Name.Equals("Alarm")));
}).ToList();
Upvotes: 1