C# 在linq to sql存储过程调用中多次枚举
我正在通过linq到sql调用一个存储过程C# 在linq to sql存储过程调用中多次枚举,c#,asp.net,linq,linq-to-sql,C#,Asp.net,Linq,Linq To Sql,我正在通过linq到sql调用一个存储过程 var qlist = dbc.GetInfoByIDandDate(ID, aDate); //sp call if (qlist.Count() == 0) { // error msg } else if (qlist.Count() > 1) { // A different Error msg. } else { GetInfoByIDandDateResult res = (GetInfoByIDandDateRe
var qlist = dbc.GetInfoByIDandDate(ID, aDate); //sp call
if (qlist.Count() == 0)
{
// error msg
}
else if (qlist.Count() > 1)
{
// A different Error msg.
}
else
{
GetInfoByIDandDateResult res = (GetInfoByIDandDateResult) qlist.First();
string x = res.fieldXname; // this is a field in the result set.
... and so on.
}
我尝试过这一点的各种化身,但总是一个错误。
此迭代的错误是“查询结果不能枚举多次”
正确的处理方法是什么?调用Count()和First()时,实际上每次都在枚举
我猜这会起作用:
var qlist = dbc.GetInfoByIDandDate(ID, aDate).ToList();
或者,更聪明的是:
var qlist = dbc.GetInfoByIDandDate(ID, aDate).Take(2).ToList();
请注意,ToList()缓存结果,以便Count()和First()不再运行查询。调用Count()和First()时,实际上每次都在枚举
我猜这会起作用:
var qlist = dbc.GetInfoByIDandDate(ID, aDate).ToList();
或者,更聪明的是:
var qlist = dbc.GetInfoByIDandDate(ID, aDate).Take(2).ToList();
请注意,ToList()缓存结果,以便Count()和First()不再运行查询。是否多次枚举结果?string results=qlist.Count==0?“错误1”:qlist.Count==1?“错误2:”(GetInfoByIDandDateResult)qlist.First().fieldXname;您还可以使用Single,而不是First,如果没有一个结果,Single将抛出异常。那么就不需要调用Count。是否多次枚举结果?string results=qlist.Count==0?“错误1”:qlist.Count==1?“错误2:”(GetInfoByIDandDateResult)qlist.First().fieldXname;您还可以使用Single,而不是First,如果没有一个结果,Single将抛出异常。那么您就不需要调用Count了。为什么它是Take(2)而不是Take(1)?我以前使用过ToList()选项,但遇到了不同的问题。我会再试一次。那一次成功了。我以前肯定有别的问题。Tx,elTake(2),因为否则else if(qlist.Count()>1)总是错误的。为什么它是Take(2)而不是Take(1)?我以前使用过ToList()选项,但遇到了不同的问题。我会再试一次。那一次成功了。我以前肯定有别的问题。Tx,elTake(2),因为否则else if(qlist.Count()>1)将始终为false