0

I have the following simple table:

table : Inventory
+-------+-----------+-----------+
|   Id  | ProductId |   cost    |
+-------+-----------+-----------+
|   1   |   1       |     10    |
|   2   |   2       |     55    |
|   3   |   1       |     42    |
|   4   |   3       |     102   |
|   5   |   2       |     110   |
+-------+-----------+-----------+

I have the following SQL query:

SELECT T.Id
FROM Inventory AS T INNER JOIN
                             (SELECT ProductId
                               FROM Inventory
                               GROUP BY ProductId
                               HAVING (COUNT(*) > 1)) AS S ON T.ProductId = S.ProductId

This works to give me all of the Ids where a duplicate ProductId exists. Using the above table, this query would return Ids { 1,2,3,5 }, which is exactly what I want.

I tried converting this into a Lambda expression, but it continually fails with the join. Can anyone get me started and point me in the right direction to write this expression?

This is what I have tried:

var q = inventory.Join( inventory.GroupBy( o => o.ProductId ).Where( o => o.Count( ) > 1 ), g => g.ProductId, gb => gb.Key, ( g, gb ) => g.Id ).ToList( );
5
  • 5
    can you show us the lambda you tried? Commented Feb 6, 2019 at 13:32
  • LINQ is not a SQL replacement. It's a query language used on top of ORMs. ORMs in turn are not meant for reporting queries like this one. Which ORM are you using anyway? Commented Feb 6, 2019 at 13:36
  • Finding duplicates in T-SQL is far easier using COUNT() OVER (PARTITION BY ProductID) or ROW_NUMBER() OVER (PARTITION BY ProductID ..) Commented Feb 6, 2019 at 13:37
  • Don't know why you need both a GroupBy and Join. You can use just the GroupBy. Commented Feb 6, 2019 at 13:41
  • You're right. The join was the issue. I was mistakenly attempting to literally adapt T-SQL to LINQ. Commented Feb 6, 2019 at 13:57

1 Answer 1

3

You need to use somthing like this:

 var result = Inventory
   .GroupBy(x => x.ProductId)
   .Where(x => x.Count() > 1)
   .SelectMany(x => x.ToList())
   .Select(x => x.Id);
Sign up to request clarification or add additional context in comments.

3 Comments

You don't need that ToList inside of the SelectMany.
Thanks @Mehrdad Dowlatabadi. You saved me a headache.
@juharr Right, thank you for the point. np,glad i could help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.