简体   繁体   中英

How to filter the List using C# LINQ

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

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

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