DCSIMG

 Subscribe in a reader

Merging To Lists Using Linq - Guy kolbis
Monday, March 31, 2008 12:44 PM kolbis

Merging To Lists Using Linq

Hi,

Here is a little sample on how to merge two lists into a single list using Linq To Objects.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        class Person
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        static void Main(string[] args)
        {
            List<Person> list = new List<Person>();
            
            for (int i = 0; i < 10000; i++)
            {
                list.Add(new Person { Id = i, Name = "guy" + i.ToString() });
            }

            List<Person> list2 = new List<Person>();

            for (int i = 5000; i < 10000; i++)
            {
                list2.Add(new Person { Id = i, Name = "guy" + i.ToString() });
            }

            var q = from first in list
                    join second in list2
                    on first.Id equals second.Id
                    select first;

            Console.WriteLine("Total: ", q.Count());

            foreach (var item in q)
            {
                Console.WriteLine("Id: {0} ; Name: {1}.", item.Id, item.Name);
            }
        }
    }
}
תגים:,

תוכן התגובה

# re: Merging To Lists Using Linq

Sasha Goldshtein כתב/ה

Or you could put the two lists in a temporary array and use Aggregate to obtain the result list.

Wednesday, April 02, 2008 9:26 AM

שלח תגובה

(שדה חובה) 
(שדה חובה) 
(אופציונלי)
(שדה חובה) 

Enter the numbers above: