I need to run a LINQ query that will return 3 rows (current record, previous record and next record relative to the current record. ProductID is my auto-generated identifier column.
I am currently doing this with the Union LINQ statement, but I'm not sure if there is a better or more efficient way to accomplish the same task.
Here is what I got:
var ProductID = 10; var Results = (from p in DB.Products where p.ProductID == ProductID - 1 //Previous record. select new Product { ProductID = p.ProductID, ProductTitle = p.ProductTitle, Views = p.Views, }).Union(from p in DB.Products where p.ProductID == ProductID //Current record select new Product { ProductID = p.ProductID, ProductTitle = p.ProductTitle, Views = p.Views, }).Union(from p in DB.Products where p.ProductID == ProductID + 1 //Next record. select new Product { ProductID = p.ProductID, ProductTitle = p.ProductTitle, Views = p.Views, });
This should return 3 rows for ProductID 9, ProductID 10, ProductID 11. Thank you!
source share