Search for values โ€‹โ€‹common to all elements

I have a dataset with two columns as follows:

Prod Value
A    1
A    2
A    3
B    2
B    4
C    1
C    2

So, I want all the rows where the value is shared by Prod, so only the following will be returned in the above example.

A   2
B   2
C   2 

It would be useful to use LINQ or sql

thank

+5
source share
3 answers
--    DROP TABLE #t2  UNCOMMENT WHEN TESTING...

CREATE TABLE #t2
(
 Prod varchar(50),
 Value int
)

INSERT INTO #t2 VALUES ('A', 1)
INSERT INTO #t2 VALUES ('A', 2)
INSERT INTO #t2 VALUES ('B', 2)
INSERT INTO #t2 VALUES ('B', 4)
INSERT INTO #t2 VALUES ('C', 2)

SELECT 
    DISTINCT
    p1.Prod, 
    p2.Value 
FROM 
    #t2 p1
INNER JOIN 
    #t2 p2 
ON 
    p2.Value = p1.Value AND p1.Prod <> p2.Prod

This is a SQL Server based solution :).

+1
source

You can use the Intersect statement in the second column of the dataset.

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var commonNumbers = numbersA.Intersect(numbersB);

Linq Samples

+1
source

This is what I came up with, I think there is an easier way, but;

        var prodList = (from col in list select col["Prod"]).Distinct().ToList();


        var valueList = from col in list
                        group col by col["Value"] into g
                        where g.Count() == prodList.Count()
                        select g.Key;

That will give me all the values โ€‹โ€‹I'm looking for

+1
source

All Articles