Home > database >  C# Linq filter list by sub list that contains a specific value
C# Linq filter list by sub list that contains a specific value

Time:10-19

I am trying to select a list of items where the item.itemApplications list contains an itemApplication.itemApplicationId == 5. Looking for the simplest cleanest way to do this to return list< item >.

{
"items": [
    {
        "itemId" : 1, 
        "itemApplications": [
            {
                "itemApplicationId": 7,
                "name": "application7",
            },
            {
                "itemApplicationId": 4,
                "name": "application4",
            }
        ]
    },
    {
        "itemId" : 2, 
        "itemApplications": [
            {
                "itemApplicationId": 3,
                "name": "application3",
            },
            {
                "itemApplicationId": 5,
                "name": "application5",
            }
        ]
    }
]

}

Hoping to filter to just return List < item >:

{
        "itemId" : 2, 
        "itemApplications": [
            {
                "itemApplicationId": 3,
                "name": "application3",
            },
            {
                "itemApplicationId": 5,
                "name": "application5",
            }
        ]
    }

CodePudding user response:

One option is to use Linq with Where and Any and select items Where itemApplications.Any has an itemApplicationId equal to whatever, in your example, 5:

public class Item
{
    public int itemId {get; set;}
    public List<ItemApplications> itemApplications { get; set; }
}

public class ItemApplications
{
    public int itemApplicationId {get; set;}
    public string name {get; set;}
}

List<Item> items = new List<Item>
{
    new Item { itemId = 1, itemApplications = new List<ItemApplications> { new ItemApplications { itemApplicationId = 7, name = "application7" }, new ItemApplications {  itemApplicationId = 4, name = "application4" } } },
    new Item { itemId = 2, itemApplications = new List<ItemApplications> { new ItemApplications {  itemApplicationId = 3, name = "application3" }, new ItemApplications {  itemApplicationId = 5, name = "application5" } } },
};

var i = items
            .Where(a => a.itemApplications
            .Any(b => b.itemApplicationId == 5))
            .ToList();

 i.ForEach(a => a.itemApplications
  .ForEach(b => Console.WriteLine($"id: {b.itemApplicationId}, name: {b.name}")));

//Prints
//id: 3, name: application3
//id: 5, name: application5

CodePudding user response:

You can get result by simply write this

  var desiredItems = (
                       from item in items
                       where item.itemApplications.Any(i => i.itemApplicationId == 5)
                       select item
                     ).ToList();
  • Related