简体   繁体   中英

How to filter navigation property of a list by LINQ and Lambda expression?

I have a list of FirstLevelItem s. Each item has a list of SecondLevelItem s.

public class FirstLevelItem {
    public List<SecondLevelItem> SecondLevelItems { get; set; }
}

public class SecondLevelItem{
    public bool Deleted {get; set;}
}

I want to return all FirstLevelItem s and filter SecondLevelItem s which are Deleted.

I understand you have a local collection and you want to filter the items that are not deleted from each element. In such case you can use this:

items.ForEach( item => 
   item.SecondLevelItems = item.SecondLevelItems.Where(s => !s.Deleted).ToList() );

Alternatively, if you are talking about a database, you could do:

var results = DataContext.FirstLevelItems.Select( fi => new { 
      FirstLevelItem = fi, 
      SecondLevelItems = fi.SecondLevelItems.Where( si => !si.Deleted ) 
} );

This will return tuples where FirstLevelItem property is the first level item itself, and SecondLevelItems property is the filtered list of second level items. However, make sure you access the SecondLevelItems property directly, not the FirstLevelItem.SecondLevelItems property, as that would lazily evaluate and query the database for all second level items.

It is interesting how everyone understood the problem differently :-) .

Return all FirstLevelItem s that contain at least one SecondLevelItem that is deleted:

var result = DbContext.FirstLevelItems
    .Where(fl => fl.SecondLevelItems.Any(sl => sl.Deleted));

The Any clause checks if a boolean condition is true for at least one item in a collection.

Suppose you have variable list of type List<FirstLevelItem> .

list = list.Select(listItem =>
{
    listItem.SecondLevelItems = listItem
        .SecondLevelItems
        .Where(secondLevelItem => secondLevelItem.Deleted)
        .ToList();
    return listItem;
}).ToList();

this code maybe help you

 var fli = //get your FirstLevelItems
       var result= fli.SecondLevelItems.Where(x => x.Deleted);

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