Click here to Skip to main content
15,888,325 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi there,

I have a entity relationship data table: vendor(1)--> inventory(many)<-- product(1), and I try to find the VendorId("A0001")'s all products with the most up-to-date inventory records.


SQL Table:

C#
InvId	   createDate	              vendorId     productId
1	       2016-03-11 21:11:09.677	  A0001	       1
2	       2016-03-11 21:26:09.647	  A0002	       1
3	       2016-03-11 21:26:09.647	  A0001	       1
4	       2016-03-11 21:26:43.707	  A0001	       5
5	       2016-03-11 21:45:03.013	  A0001	       1
6	       2016-03-11 21:26:09.647	  A0003	       2



can anyone help me with the linq statement?

What I have tried:

var parents = joda.inventory.AsEnumerable().Where(row => row.vendorId == vendorId);

var childProdcut = joda.inventory.AsEnumerable().Where(row => parents.Any(p => p.productId == row.productId && row.moveOut != "Y")).OrderBy(row => row.productId).First();

The result has duplicated productIds.
Posted
Updated 14-Mar-16 14:03pm

1 solution

I'm a bit irritated by the fact that you've shown a column moveOut in "What you have tried" but not in your table - but the following should at least give you an idea, if its not exactly what you want.

Key points: Grouping the rows by productId, then in each productId-group order the rows by their createDate so that the latest appears first, then taking the first one and getting the InvId of it:
C#
var results = joda.inventory.AsEnumerable()
    .Where(row => row.vendorId == vendorId)
    .GroupBy(row => row.productId)
    .Select(grp => new
    {
        productId = grp.Key,
        invId = grp.OrderByDescending(row => row.createDate).First().InvId
    });

The result results is an enumeration (or a List, if you append a .ToList() at the end) of an "anonymous type" which holds the productId and the invId. If you need help with dealing with an "anonymous type" please leave a comment.
 
Share this answer
 
v3
Comments
Pai809 15-Mar-16 9:44am    
Oh MY, I forgot to remove the "moveOut" column, anyway Thanks for the solution, It works.
Sascha Lefèvre 15-Mar-16 9:59am    
You're welcome, glad it worked for you! Feel free to mark the solution as 'accepted' ;-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900