how can I convert IQueryable<string> to string?

徘徊边缘 提交于 2019-12-17 19:34:02

问题


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?


回答1:


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)



回答2:


To get the first element in your query, you can use query.First() but if there are no elements, that would throw an exception. Instead, you can use query.FirstOrDefault() which will give you either the first string, or the default value (null). So for your query this would work:

var myString = (from Comp in ServiceGroupdb.ServiceGroupes 
               where Comp.GroupID == groupID
               select Comp.Name)
               .FirstOrDefault();



回答3:


You're almost there.

Just do

IQueryable<string> query = from Comp in ServiceGroupdb.ServiceGroupes where (Comp.GroupID == groupID) select Comp.Name;
// Loop over all the returned strings
foreach(var s in query)
{
    Console.WriteLine(s);
}

Or use query.FirstOrDefault() as mentioned as you'll only get one result.




回答4:


I find the methods'way is prettier and clearer, so here it goes:

string query = ServiceGroupdb.ServiceGroupes
               .Where(Comp => Comp.GroupID == groupID)
               .Select(Comp => Comp.Name)
               .FirstOrDefault();



回答5:


Just do it like this;

var query = from Comp in ServiceGroupdb.ServiceGroupes where (Comp.GroupID == groupID) select Comp.Name;

query will then contain your result.



来源:https://stackoverflow.com/questions/11326468/how-can-i-convert-iqueryablestring-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!