how can I convert IQueryable<string> to string?

只愿长相守 提交于 2019-11-28 10:56:48

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)
Filip Ekberg

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();

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.

Alex

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();

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.

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