Linq to SQl

I was playing with Linq to Sql and I was wondering if it is possible to get one result? 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 that, I need to do a foreach around the client var, but I know it will be one value! Does anyone know how I can do "textbox.text = c.name;" or something along that line ...

0


source to share


2 answers


Yes it is 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 is no result.



You can also use Single (), which throws an exception if there is no result. First () will only give you the first result it finds, where Last () will only give you the last result, if any.

See here for an overview of all Enumerable methods.

+5


source


var customer = context.table.SingleOrDefault(c => c.ID == textboxvalue);

      



+2


source







All Articles