Sql – Linq to SQl

linq-to-sql

I have been playing with the Linq to Sql and i was wondering if it was possible to get a single result out? for example, i have the following:

using(DataClassContext context = new DataClassContext())
{
var customer = from c in context.table
where c.ID = textboxvalue
select c;
}

And with this i need to do a foreach around the var customer but i know that this will be a single value! Anyone know how i could do a "textbox.text = c.name;" or something along that line…

Best Answer

Yes, it's possible.

using(DataClassContext context = new DataClassContext())
{
var customer = (from c in context.table
where c.ID = textboxvalue
select c).SingleOrDefault();
}

This way you get 1 result or null if there isn't any result.

You can also use Single(), which throws an exception when there isn't a result. First() will give you only the first result found, where Last() will give you only the last result, if any.

Here's an Overview of all Enumerable methods.