c# – Need help with merging two data collections – Education Career Blog

I need to retrieve all items from two lists that contains a given value.

Example:

var list1 = {
    new Dummy(){ Name = "Dummy1", Number = 1 },
    new Dummy(){ Name = "Dummy2", Number = 2 },
    new Dummy(){ Name = "Dummy3", Number = 3 }
};

var list2 = {
    new Dummy(){ Name = "Dummy4", Number = 4 },
    new Dummy(){ Name = "Dummy5", Number = 2 },
    new Dummy(){ Name = "Dummy6", Number = 6 }
};

var list3 = GetAllDummiesWithNumbersContainedInBothLists();

I want list3 to contain Dummy2 and Dummy5, since both have the same number.

How do i do this? It should be simple but i cant figure it out…

,

See if this works for you:

(from dummy1 in list1
join dummy2 in list2 on dummy1.Number equals dummy2.Number
from dummy in new { dummy1, dummy2 }
select dummy)
.Distinct()

This pairs matching dummies into the same scope, then flattens out the set so you get all of the matches in one sequence. The Distinct at the end ensures that each dummy appears exactly once even if either list contains repeated numbers.

,

I’m not entirely sure what your requirements are, but something like this perhaps?

var commonIds = list1.Select(d => d.Number)
                     .Intersect(list2.Select(d => d.Number));

var commonIdsSet = new HashSet<int>(commonIds);

var list3 = list1.Concat(list2)
                 .Where(d => commonIdsSet.Contains(d.Number))
                 .ToList();

if you can clarify the exact requirements (do the results need to be grouped by theNumber, IsNumberunique for an item within a list etc.), we can provide better solutions.

,

var list3 = list1.Where(d => list2.Select(d2 => d2.Number).Contains(d.Number))
    .Union(list2.Where(d2 => list1.Select(d => d.Number).Contains(d2.Number)));

,

Here’s one more!

var list3 = list1
  .SelectMany(x => list2
   .SelectMany(y => 
    (y.Number == x.Number) ? new  { x, y } : new Dummy{}
   )
  );

Leave a Comment