当没有行时如何处理 CopyToDataTable()?
我有代码:
dt = collListItems.GetDataTable().AsEnumerable()
.Where(a => Convert.ToString(a["Expertise"]).Contains(expertise) && Convert.ToString(a["Office"]) == office)
.CopyToDataTable();
filteredCount = dt.Rows.Count();
当没有匹配的行时,我应该如何最好地处理该事件?目前我得到
源不包含数据行
,但在这种情况下我想将 FilteredCount 设置为 0。
我知道 try-catch 有效,但是有更优雅的方法吗?
I have the code:
dt = collListItems.GetDataTable().AsEnumerable()
.Where(a => Convert.ToString(a["Expertise"]).Contains(expertise) && Convert.ToString(a["Office"]) == office)
.CopyToDataTable();
filteredCount = dt.Rows.Count();
How should I best handle the event when there are no rows that match? Currently I get
The source contains no DataRows
but I want to set filteredCount to 0 in that case.
I know a try-catch works, but is there a more elegant way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您当然不想为此使用 try/catch。 Try/Catch 应该在真正的特殊情况下使用,您不希望让它驱动您的控制流。几乎在所有情况下,都有更好的方法直接内置于语言/库中或需要最少的编码工作。
在这种情况下,您需要预先捕获表,这样就不会调用
GetDataTable()
方法超过必要的次数,因为如果查询不包含任何结果,我们将需要它。如果查询本身成本高昂或运行时间较长,您还可以选择在查询中包含ToList()
,因此您只需执行一次。然后,需要测试结果中是否有任何行。如果是这样,您可以安全地复制到数据表。否则,只需克隆原始表的结构(不包括行),这样在任何一种情况下,您都有一个正确的表结构,并且可以检查行数,将其绑定到控件,等等,并没有什么意外。
You certainly do not want to use a try/catch for this. Try/Catch should be used in truly exceptional circumstances, you do not want to have it drive your control flow. In nearly all situations, there are better methods that are built right into the language/library or require minimal effort to code.
In this case, you want to capture the table beforehand so that you do not invoke the
GetDataTable()
method more times than necessary, because we're going to need it if the query does not include any results. You could also optionally includeToList()
on the query if the query itself is expensive or long-running, so you only need to do that once.Afterwards, it's a matter of testing if there are any rows in the result. If so, you can safely copy to a datatable. Otherwise, just clone the structure of the original table (will not include the rows), so that in either case, you have a proper table structure and can inspect the row count, bind it to a control, etc., and there are no surprises.
这个解决方案怎么样:
data.Tables[0]
是源表,filtered_data
是结果表。How about this solution :
data.Tables[0]
is the source table andfiltered_data
is the resultant table.可以先判断是否有匹配的行:
you can first judge whether there are rows that match:
我认为这将是一个更简单的解决方案:
I think this would be a simpler solution:
下面的代码对我有用。请尝试
Below code works for me. please try
可重用的通用解决方案:
创建一个扩展方法:
现在您可以像这样调用此扩展方法:
Reusable generic solution:
Create an extension method:
Now you can call this extension method like:
您可以使用扩展方法 Any(): 在使用 CopyToDataTable() 之前进行检查以避免 No Datarow found 异常
You can use the extension method Any(): to check before using CopyToDataTable() to avoid No Datarow found exception