none
Merge properties of anonymous type object RRS feed

  • Question

  • Hi, 

    I have two lists:

    List<T> elements

    List<T> contents

    Both have common property called ID. Other properties are different. I want to merge both the above lists into single list. I want to check whether ID is equal for both objects before merging. Please let me know how this can be achieved.

    Thank you.

    Regards,

    Kiran

    Wednesday, April 29, 2015 4:26 PM

Answers

  • Consider the next possibility:

    static IEnumerable<Tuple<A, B>> Merge<A, B>( IEnumerable<A> A_items, IEnumerable<B> B_items )

    {

           var results =

                  A_items

                         .Select( a => new Tuple<A, B>( a, B_items.FirstOrDefault( b => ( (dynamic)b ).ID == ( (dynamic)a ).ID ) ) )

                         .Where( t => t.Item2 != null );

           return results;

    }

    But since it returns Tuples, you will have to use Item1 and Item2 members in order to access the merged properties.

    Thursday, April 30, 2015 4:31 PM

All replies

  • Check the next example:

    var result =

           contents

                  .Select( c => new { c, e = elements.FirstOrDefault( e => e.ID == c.ID ) } )

                  .Where( z => z.e != null )

                  .Select( z => new { z.c.ID, z.e.Name, z.c.Age } );

    It supposes that elements consists of ID and Name and contents consists of ID and Age, and ID is unique in each list. Adjust it according to the number and names of your fields.

    Wednesday, April 29, 2015 8:23 PM
  • Hi Viorel,

    Thanks for your response. As it's anonymous type, every time there will be different count and names of properties. Is there a way to make this work for all of them ? The result should be of type List<T>.

    Regards,

    Kiran

    Thursday, April 30, 2015 4:37 AM
  • Consider the next possibility:

    static IEnumerable<Tuple<A, B>> Merge<A, B>( IEnumerable<A> A_items, IEnumerable<B> B_items )

    {

           var results =

                  A_items

                         .Select( a => new Tuple<A, B>( a, B_items.FirstOrDefault( b => ( (dynamic)b ).ID == ( (dynamic)a ).ID ) ) )

                         .Where( t => t.Item2 != null );

           return results;

    }

    But since it returns Tuples, you will have to use Item1 and Item2 members in order to access the merged properties.

    Thursday, April 30, 2015 4:31 PM