Csharp/C#教程:如何将IQueryable 转换为字符串?分享


如何将IQueryable 转换为字符串?

我做一个sql查询,它返回一个字符串 – 服务名称。 这是查询:

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

如何从查询中获取字符串?

LINQ始终返回一个序列,因此您必须从中检索项目。 如果您知道只有一个结果,请使用Single()来检索该项目。

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

有四种LINQ方法可以从序列中检索单个项目:

要获取查询中的第一个元素,可以使用query.First()但如果没有元素,则会引发exception。 相反,您可以使用query.FirstOrDefault() ,它将为您提供第一个字符串或默认值( null )。 所以对于你的查询,这将工作:

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

你快到了。

做就是了

 IQueryable 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); } 

或者使用query.FirstOrDefault() ,因为你只会得到一个结果。

我发现这些方法更漂亮,更清晰,所以这里有:

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

就这样做;

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

然后查询将包含您的结果。

上述就是C#学习教程:如何将IQueryable 转换为字符串?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1023973.html

(0)
上一篇 2022年1月8日
下一篇 2022年1月8日

精彩推荐