Home > Enterprise >  How to filter child entity with Linq?
How to filter child entity with Linq?

Time:09-17

For example, I would like to return dto with value 1, but only show child items that match the query. Is it possible to do it by querying the parent entity, or need to be done "manually" on child entity?

using System;
using System.Linq;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        
        List<Dto> dtos = new List<Dto>();
        var items = new List<Item>();
        items.Add(new Item(){ Value = 5});
        items.Add(new Item(){ Value = 6});
        
        var dtos2 = dtos.Where(a=>a.Items.Any(x=>x.Value == 8));
        
        dtos.Add(new Dto()
                 {
                      Id = 1,
                     Items =  items
                 });

        
        
        foreach(var item in dtos2)
        {
            Console.WriteLine(item.Id);
            
            foreach(var item2 in item.Items)
            {
                Console.WriteLine(item2.Value);
            }
        }
    }
    

The DTO classes are

    public class Dto
    {
        public int Id {get;set;}
        public List<Item> Items {get;set;}
    }
    
    public class Item
    {
    public int Value {get;set;} 
    }
            
}

CodePudding user response:

It's not possible without mutating the Items property or instantiating new Dto objects.

Mutational operations, whilst possible, shouldn't be attempted using LINQ which is designed for querying.

However, if you're happy with allocating new objects, you could take this approach:

var dtos2 = dtos.Select(a => new Dto
{
    Id = a.Id,
    Items = a.Items.Where(x => x.Value == 8).Tolist()
});

This has the benefit of keeping the original dtos unchanged.

  • Related