views:

66

answers:

4

Hello!

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...

+1  A: 
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)));
Justin Niessner
Not quite. That returns a `bool`.
Ahmad Mageed
@Ahmad - Yeah. I had two different answers merged together and forgot to change the last bit. Done.
Justin Niessner
@Ani - Yes, it would. Needed to Union the results looking the other way.
Justin Niessner
+1  A: 

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.

Ani
+2  A: 

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.

Bryan Watts
A: 

Here's one more!

var list3 = list1
  .SelectMany(x => list2
   .SelectMany(y => 
    (y.Number == x.Number) ? new [] { x, y } : new Dummy[]{}
   )
  );
diceguyd30
I freely admit, it is probably not the best, but Justin posted my original answer first so I felt compelled to discover another way!
diceguyd30