Returning a single object with LINQ to SQL

Posted Thursday, January 17, 2008 4:42 PM by C-Dog's .NET Tip of the Day

I have been messing around with LINQ (both with SQL and XML) and am pretty familiar with the query syntax right now, but I wasn't sure at first how to get a single object. It's actually pretty simple using a lambda expression. Assume I have a simple table called Products and it has fields Name and Id and we're looking for a product with an id of 45. After dragging the table into a new LINQ to SQL class, you can begin the process of querying it. Here is how it works.

ProductsDataContext dataContext = new ProductsDataContext();
Product myProduct 
= dataContext.Products.Single(p => p.Id == 45)

That's all there is to it. Get a reference to your data context and then you will have intellisense into the Products table. The method Single takes a lambda expression. In this case p can be named whatever (except the name myProduct), and it again provides you intellisene into the Products table. This makes it really simple to get a single item when you are cowboy coding data access with LINQ to SQL.

Read the complete post at

Filed under: