Alex Rivera | Logout

Lambda Expression to filter a list of list of items

Asked 2012-03-21T19:07:20.573
14

I have a a list of list of items and I was wondering if someone could help me with a lambda expression to filter this list.

Here's what my list looks like:

List<List<Item>> myList = ExtractList();

Here's what my Item class looks like:

public class Item {
    public string Name {get;set;}
    public string Action {get;set;}
}

I would like to filter this list and get only those List of List of Items where the Item Name = "ABC" and item Action = "123".

Thanks for any help

Edit
Report

2 Answers

35

Simple:

myList.SelectMany(sublist => sublist)
    .Where(item => item.Name == "ABC" && item.Action == "123");

This gives you all the items inside all the lists.

If you want to select sublists that contain the item instead:

myList.Where(sublist => sublist.Any(item => item.Name == "ABC" && item.Action == "123"));

And lastly if you want to preserve the same structure but only keep the items that match the filter:

var newList = myList.Select(sublist => sublist
                       .Where(item => item.Name == "ABC" && item.Action == "123")
                       .ToList()).ToList();
answered 2012-03-21T19:10:13.333
1

This may work;

List<Item> Items = new List<Item>();

myList.ForEach((item)=>
{
   var items = item.Where(q=> q.Action == "123" && q.Name =="ABC");
   Items.AddRange(items);
});
answered 2012-03-21T19:21:12.553

Your Answer