How to efficiently aggregate several collections into one collection?

How to use LINQ to combine two or more collections into one collection

  • I have three collections var col1 = new {Name1 = "Frank", ID1 = 123, ABC = "abc"}; var col2 = new {Name2 = "Harry", ID2 = 456, XYZ = "xyz"}; var col3 = new {Name3 = "Bob"}; I want to create a fourth collection that brings those three collections together. Using the three collections as the example, I would like the fourth collection to "look" like this: +===================+ | FirstName | Ident | +===================+ | Frank | 123 | +-------------------+ | Harry | 456 | +-------------------+ | Bob | | +-------------------+ I don't even know if it's possible, but I'm trying to figure out if I can use LINQ to merge the tables by mapping the fields of col1, col2, and col3 to the fields of the fourth collection. Psuedo-code to, hopefully, clarify what I'm trying to explain: var col4 = from c1 in col1, c2 in col2, c3 in col3 select new {FirstName = (c1.Name1, c2.Name2, c3.Name3), Ident = (c1.ID1, c2.ID2); If this is possible, how can I accomplish this?

  • Answer:

    You can use Linq Union. I've faked up the initialization since your example doesn't really have collections, but still retain the anonymous nature of the elements since I think this is what you're intending. static void Main(string[] args) { var dummys = new List<int>(); dummys.Add(1); var col1 = from dummy in dummys select new { Name1 = "Frank", ID1 = 123, ABC = "abc" }; var col2 = from dummy in dummys select new { Name2 = "Harry", ID2 = 456, XYZ = "xyz" }; var col3 = from dummy in dummys select new { Name3 = "Bob" }; var col4 = col1.Select(c=> new { FirstName=c.Name1, Ident=new Nullable<int>(c.ID1)}) .Union(col2.Select(c=> new { FirstName=c.Name2, Ident=new Nullable<int>(c.ID2)})) .Union(col3.Select(c=> new { FirstName=c.Name3, Ident=new Nullable<int>()})); foreach (var c in col4) { Console.WriteLine(c); } Console.ReadKey(); }

Jed at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

I think you're looking for LINQ Union operator: http://msdn.microsoft.com/en-us/library/system.linq.enumerable.union.aspx

twaggs

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.