简体   繁体   English

如何转换IQueryable <string> 串起来?

[英]how can I convert IQueryable<string> to string?

I do a sql query which returns a string - service name. 我做一个SQL查询,返回一个字符串-服务名称。 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. LINQ总是返回一个序列,因此您必须从中检索该项目。 If you know that you will have only one result, use Single() to retrieve that item. 如果知道只有一个结果,请使用Single()检索该项目。

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: 有四种LINQ方法可从序列中检索单个项目:

  • Single() returns the item, throws an exception if there are 0 or more than one item in the sequence. Single()返回该项目,如果序列中有0个或多个项目,则引发异常。
  • SingleOrDefault() returns the item, or default value ( null for string ). SingleOrDefault()返回该项或默认值( stringnull )。 Throws if more than one item in the sequence. 如果序列中有多个项,则抛出该异常。
  • First() returns the first item. First()返回第一项。 Throws if there are 0 items in the sequence. 如果序列中有0个项目,则抛出该异常。
  • FirstOrDefault() returns the first item, or the default value if there are no items) FirstOrDefault()返回第一个项目,如果没有项目则返回默认值)

To get the first element in your query, you can use query.First() but if there are no elements, that would throw an exception. 要获取查询中的第一个元素,可以使用query.First()但是如果没有元素,则将引发异常。 Instead, you can use query.FirstOrDefault() which will give you either the first string, or the default value ( null ). 相反,您可以使用query.FirstOrDefault() ,这将为您提供第一个字符串或默认值( 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. 或使用提到的query.FirstOrDefault() ,因为您只会得到一个结果。

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. 查询将包含您的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM