I do a sql query which returns a string - service name. this is the query:
IQueryable<string> query = from Comp in ServiceGroupdb.ServiceGroupes
where (Comp.GroupID == groupID)
select Comp.Name;
How do i get the string out of the query?
LINQ always returns a sequence, so you have to retrieve the item out of it. If you know that you will have only one result, use Single()
to retrieve that item.
var item = (from Comp in ServiceGroupdb.ServiceGroupes
where (Comp.GroupID == groupID)
select Comp.Name).Single();
There are four LINQ methods to retrieve a single item out of a sequence:
Single()
returns the item, throws an exception if there are 0 or more than one item in the sequence.SingleOrDefault()
returns the item, or default value (null
for string
). Throws if more than one item in the sequence.First()
returns the first item. Throws if there are 0 items in the sequence.FirstOrDefault()
returns the first item, or the default value if there are no items)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With