没有行时如何处理CopyToDataTable()? [英] How to handle CopyToDataTable() when no rows?

查看:264
本文介绍了没有行时如何处理CopyToDataTable()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码:

dt = collListItems.GetDataTable().AsEnumerable()
        .Where(a => Convert.ToString(a["Expertise"]).Contains(expertise) && Convert.ToString(a["Office"]) == office)
         .CopyToDataTable(); 

filteredCount = dt.Rows.Count();

当没有匹配的行时,如何最好地处理事件?当前,我得到源不包含DataRows,但在那种情况下我想将filteredCount设置为0。

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.

预先感谢。

编辑:我知道可以尝试try..catch,但是还有一种更优雅的方法吗?

I know a try..catch works but is there a more elegant way?

推荐答案

您当然不想为此使用try / catch。 Try / Catch应该在真正的特殊情况下使用,您不想让它驱动控制流。在几乎所有情况下,语言/库中都内置了更好的方法,或者需要很少的代码编写工作。

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.

在这种情况下,您要捕获表事先避免您调用 GetDataTable()方法的次数不必要,因为如果查询不包含任何结果,我们将需要它。如果查询本身是昂贵的或长时间运行的,则还可以选择在查询中包括 ToList(),因此只需要执行一次即可。

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 include ToList() 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.

var table = collListItems.GetDataTable();    
var rows = table.AsEnumerable().Where(...); // optionally include .ToList();
var dt = rows.Any() ? rows.CopyToDataTable() : table.Clone();
int filteredCount = dt.Rows.Count;

这篇关于没有行时如何处理CopyToDataTable()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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