Search code examples
c#linqcollectionslinq-to-objectsdto

LINQ for querying a DTO for a specific Name-Value pair in a generic and recursive manner


I have a DTO which is composed of a series of collections. Each of these collections again hold various name-value pairs in their InnerLists.

Is there a way to query the DTO for a specific name and get its value...irrespective of the Collection or the position in the InnerList it is in?


Solution

  • You can use a pattern like this. Notice how I have two different collections in my class but I am exposing a unified iterator, which is used in Main function to treat it like one collection and print out all the even elements in all collections.

     class Foo : IEnumerable<int>
        {
            List<int> first = new List<int>();
            List<int> second = new List<int>();
    
    
            public Foo()
            {
                first.Add( 1 );
                first.Add( 2 );
    
                second.Add( 11 );
                second.Add( 12 );
            }
    
    
            public IEnumerator<int> GetEnumerator()
            {
                foreach (var f in first)
                {
                    yield return f;
                }
    
                foreach (var f in second)
                {
                    yield return f;
                } 
            }
        }
    
        static void Main(string[] args)
        {
            Foo f = new Foo();
    
            foreach (var d in f.Where(x => x % 2 == 0))
            {
                Console.WriteLine(d);
            }
    
    
            Console.ReadLine();
        }