-1

I have a Tuple list consisting of an Id (Item1) and a Value (Item2) as follows:

var tupleList = new List<Tuple<int, int>>
{
   Tuple.Create( 100, 1 ),
   Tuple.Create( 100, 1 ),
   Tuple.Create( 100, 2 ),
   Tuple.Create( 101, 1 ),
   Tuple.Create( 101, 2 ),
   Tuple.Create( 101, 3 ),
   Tuple.Create( 102, 1 ),
   Tuple.Create( 102, 2 ),
   Tuple.Create( 102, 3 )
 };

The goal is to find the common Values (Item2) between every grouped Id (Item1) and add them to an integer array. Using this example, the Ids should be grouped as 100, 101 and 102. Then, I need to extract only the values that are common to ALL groups.

In other words, using the above example, the final output would be:

{ 1, 2 }

Notice also that I added a duplicate entry for 100 as a test - not sure if that is even necessary.

I hope that makes sense. Apologies for not providing any code as I am not even sure how to begin coding this.

Scho
  • 351
  • 1
  • 2
  • 12

1 Answers1

1

This is an approach to consider:

var count = tupleList.Select(z => z.Item1).Distinct().Count();
var allThere = tupleList
    .GroupBy(z => z.Item2)
    .Where(z => z.Distinct().Count() == count)
    .Select(z => z.Key)
    .ToList();

The first line gets the number of unique Item1 values.

The second line groups the original inputs by the Item2 and then counts the number of rows. If the count is the same as the count then they must have all been there.

mjwills
  • 23,389
  • 6
  • 40
  • 63