查询结果枚举多次
datacontextclass dc=new datacontextclass ();
var news= dc.GetNewsCompany(Int64.Parse ( _idCompany));
if (news.GetEnumerator().MoveNext())
{
foreach (var item in news)
{
drpListNews.Items.Add(item.Title);
}
}
return error:{"查询结果不能被枚举多次。"}
如何在 LINQ 中检查 result != null;
datacontextclass dc=new datacontextclass ();
var news= dc.GetNewsCompany(Int64.Parse ( _idCompany));
if (news.GetEnumerator().MoveNext())
{
foreach (var item in news)
{
drpListNews.Items.Add(item.Title);
}
}
return error:{"The query results cannot be enumerated more than once."}
how can check result != null in LINQ;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
疯狂地使用枚举器是一个坏主意 - 例如,它需要处置 - 您还没有这样做(这可能导致
SqlDataReader
保持打开状态 - 不好)。在这种情况下,只需枚举它。如果没有任何记录,那就很简单:如果您需要数据两次,请将其放入列表中:
Using an enumerator wildly is a bad idea - for example, it needs disposing - which you haven't done (this could lead to a
SqlDataReader
being left open - not good). In this case, just enumerate it. If there aren't any records, that will be trivial:If you need the data twice, put it in a list:
您正在创建枚举器两次。第一个是通过调用
news.GetEnumerator()
,第二个是在foreach
循环的幕后发生。通过调用MoveNext
进行的第一个“检查”似乎没有必要(除非有要迭代的项目,否则您不会进入foreach
),所以只需跳过包装循环的if
语句:You are creating the enumerator twice. The first is by calling
news.GetEnumerator()
, the second one happens behind the scenes in theforeach
loop. The first "check" that you make with the call toMoveNext
does not seem necessary (you will not go into theforeach
unless there are items to iterate over), so just skip theif
statement wrapping the loop:将代码的第二行更改为
它可以解决问题。
Change the second line of your code to
it shall remove the issue.