how can I convert IQueryable<string> to string?

thechmodmaster picture thechmodmaster · Jul 4, 2012 · Viewed 32.9k times · Source

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?

Answer

Anders Abel picture Anders Abel · Jul 4, 2012

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)