如何返回 IEnumerable?
我正在尝试返回 IEnumerable。这是我的代码:
public static IEnumerable<int> GetAnswersIDs(int id)
{
using (var context = new MvcApplication4.Entity.test2Entities1())
{
return (from p in context.post
where p.post_parentid == id && p.post_isdeleted == false
select new
{
p.post_id
}).ToList();
}
}
是否可以返回 IEnumerable 对象?
I am trying to return an IEnumerable. Here is my code:
public static IEnumerable<int> GetAnswersIDs(int id)
{
using (var context = new MvcApplication4.Entity.test2Entities1())
{
return (from p in context.post
where p.post_parentid == id && p.post_isdeleted == false
select new
{
p.post_id
}).ToList();
}
}
Is it possible to return an IEnumerable object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不需要使用任何 To[Anything] 方法或类似的方法。你的错误是你选择的方式。正确的代码是这样的:
正如您所看到的,您创建了一个您不需要的匿名类,因为您只需要一个 int 值。
-- 编辑 --
您将面临 ObjectDispose 异常。因为当您使用返回的 IEnumerable 对象时,它需要使用 GetAnswersIDs 方法中配置的上下文。
因此,您可以返回一个 List 而不是 IEnumerable,或者您应该在 GetAnswersIDs 方法之外定义上下文。
这是带有列表的代码
You dont need to use any To[Anything] method or something like that. Your mistake is your select way. The correct code is this:
As you see you created an anonymous class which you dont need because you want just an int value.
-- EDIT --
You will be faced to an ObjectDisposed Exception. Becase when you use the returned IEnumerable object it need to use the context which disposed in the GetAnswersIDs method.
So you could return a List instead of IEnumerable or you should define the context out of your GetAnswersIDs method.
This is the code with List
我认为你应该使用
ToArray
或ToList
(Array
和List
都实现IEnumerable
),因为当您返回时,上下文已被释放,我几乎确定如果您使用AsEnumerable
将枚举本身留给后续步骤,您会得到一个异常:BTW ,我认为在您的情况下,使用 linq 比非 linq 版本更详细:
作为旁注,您可能需要考虑重新格式化模型中的字段名称以满足 .NET 中的命名约定。
I think you should use
ToArray
orToList
(bothArray<T>
andList<T>
implementIEnumerable<T>
), since when you return, the context is disposed, I am nearly sure you will get an exception if you useAsEnumerable
leaving the enumeration itself for later steps:BTW, I think in your case using linq is more verbose than the non-linq version:
As a side note, you might want to consider reformatting the field names in your model to meet the naming convensions in .NET.
我认为您正在寻找
AsEnumerable()
:但是,在查看代码后,您必须完全具体化查询结果,因此使用
ToList()
是合适的 - 否则当您稍后尝试枚举结果时,您将得到异常,因为它将尝试访问已处置的数据库上下文上的数据库。I think you are looking for
AsEnumerable()
:However after looking at your code you have to fully materialize the results from the query so using
ToList()
is appropriate - otherwise you will get an exception when you later try to enumerate the results, since it will try to access the DB on a disposed DB context.我认为您不需要
选择新的{}
select p.post_id
应该就足够了!然后你可以用.AsEnumerable()
包围它I don't think you'll need a
select new {}
select p.post_id
should be sufficient! Then you can surround it with an.AsEnumerable()
对于基本 IEnumerable 返回,使用 yield return
For the base IEnumerable return, yield return is used