使用以下linq查询时出现错误 [英] I am getting error when using following linq query

查看:93
本文介绍了使用以下linq查询时出现错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string a = list.Where(x => x.GalleyLocation ==G1)。选择(x => x.LengthOfArm).ToString();





错误:System.Linq.Enumerable + WhereSelectListIterator`2







请求帮助以了解错误原因并提供相同的解决方案

string a=list.Where(x => x.GalleyLocation == "G1").Select(x => x.LengthOfArm).ToString();


error:System.Linq.Enumerable+WhereSelectListIterator`2



please need help to know reason for error and also provide the solution for same

推荐答案

您的查询不会返回单个项目:它返回一个IEnumerable与您的条件匹配的项目。因此,当您获取集合的ToString时,您将获得集合的名称 - 这就是您获得的消息。



一般来说,尝试转换任何收集到单个字符串是一个糟糕的想法,但你可能会得到你想要的方式:

Your query does not return a single item: it returns an IEnumerable of items which match your condition. So when you take the ToString of the collection, you get the name of the collection - and that's the "message" you get.

Generally speaking, trying to convert any collection into a single string is a poor idea, but you might get what you want this way:
string a=string.Join("", list.Where(x => x.GalleyLocation == "G1").Select(x => x.LengthOfArm.ToString()));


如前所述,Select将返回一个集合,即使该集合中只有一个项目。如果您在Select中执行ToString,那么它将返回一个IEnumerable字符串,您可以在该集合上使用FirstOrDefault来获取集合中的第一个。



As already said, Select will return a collection, even if that collection only has a single item in it. If you do the ToString inside the Select then it will return an IEnumerable of string, and you can use FirstOrDefault on that collection to get the first one in the collection.

string a=list.Where(x => x.GalleyLocation == "G1").Select(x => x.LengthOfArm.ToString()).FirstOrDefault();





如果收集是空的,你会得到该类型的默认值,因此它将为字符串返回null。如果该集合中只有一个项目,那么你得到那个项目,如果它有多个项目你得到第一个项目而其余项目被忽略。



如果你想要为了确保列表中只有一个项目,您可以使用SingleOrDefault,如果列表中有多个项目,则会引发异常。这通常是一个坏主意。



If the collection is empty you'll get the default value for that type, so it'll return null for strings. If the collection has only one item in it then you get that item, if it has multiple items you get the first one and the rest are ignored.

If you want to ensure there was only one item in the list then you can use SingleOrDefault and that will raise an exception if there was more than one item in the list. This is usually a bad idea though.


这篇关于使用以下linq查询时出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆