Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I convert IQueryable<string> to string?

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?

like image 646
thechmodmaster Avatar asked Jul 04 '12 09:07

thechmodmaster


1 Answers

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)
like image 163
Anders Abel Avatar answered Sep 22 '22 01:09

Anders Abel