当没有行时如何处理 CopyToDataTable()?

发布于 2024-12-10 19:29:33 字数 436 浏览 0 评论 0原文

我有代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

无语# 2024-12-17 19:29:33

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

在这种情况下,您需要预先捕获表,这样就不会调用 GetDataTable() 方法超过必要的次数,因为如果查询不包含任何结果,我们将需要它。如果查询本身成本高昂或运行时间较长,您还可以选择在查询中包含 ToList(),因此您只需执行一次。

然后,需要测试结果中是否有任何行。如果是这样,您可以安全地复制到数据表。否则,只需克隆原始表的结构(不包括行),这样在任何一种情况下,您都有一个正确的表结构,并且可以检查行数,将其绑定到控件,等等,并没有什么意外。

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;

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 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;
小霸王臭丫头 2024-12-17 19:29:33

这个解决方案怎么样:

            DataRow[] filtered_rows = data.Tables[0].Select(filter_string);

            if(filtered_rows.Length > 0)
            {
                filtered_data = filtered_rows.CopyToDataTable();
            }
            else
            {
                filtered_data.Clear();
            }

data.Tables[0] 是源表,filtered_data 是结果表。

How about this solution :

            DataRow[] filtered_rows = data.Tables[0].Select(filter_string);

            if(filtered_rows.Length > 0)
            {
                filtered_data = filtered_rows.CopyToDataTable();
            }
            else
            {
                filtered_data.Clear();
            }

data.Tables[0] is the source table and filtered_data is the resultant table.

咿呀咿呀哟 2024-12-17 19:29:33

可以先判断是否有匹配的行:

var rows = collListItems.GetDataTable().AsEnumerable()
        .Where(a => Convert.ToString(a["Expertise"]).Contains(expertise) && Convert.ToString(a["Office"]) == office);
DataTable dt = table.Clone();
if (rows.Count() > 0)
    dt = rows.CopyToDataTable();

you can first judge whether there are rows that match:

var rows = collListItems.GetDataTable().AsEnumerable()
        .Where(a => Convert.ToString(a["Expertise"]).Contains(expertise) && Convert.ToString(a["Office"]) == office);
DataTable dt = table.Clone();
if (rows.Count() > 0)
    dt = rows.CopyToDataTable();
屋顶上的小猫咪 2024-12-17 19:29:33

我认为这将是一个更简单的解决方案:

var Adj = (from c in View.AdjustmentsDataSource.AsEnumerable()
            where c["Adjustment"] != System.DBNull.Value
            select c);

if (Adj == null || Adj.Count() == 0)
     return;

DataTable dtChanges = Adj.CopyToDataTable();

I think this would be a simpler solution:

var Adj = (from c in View.AdjustmentsDataSource.AsEnumerable()
            where c["Adjustment"] != System.DBNull.Value
            select c);

if (Adj == null || Adj.Count() == 0)
     return;

DataTable dtChanges = Adj.CopyToDataTable();
度的依靠╰つ 2024-12-17 19:29:33
var results = from myRow in dtL1Users.AsEnumerable()
                                          where (Convert.ToInt32(myRow["No_x0020_of_x0020_L1_x0020_Remin"]) >= Convert.ToInt32(maxL1Escalation) && Convert.ToDateTime(myRow["L2_x0020_Last_x0020_Escalated_x0"]) < DateTime.Now.Date.AddDays(-Convert.ToInt32(reminderinterval)))
                                          select myRow;

                            foreach (var v in results)
                            {
                                collEligible = results.CopyToDataTable<DataRow>();
                                break;
                            }
var results = from myRow in dtL1Users.AsEnumerable()
                                          where (Convert.ToInt32(myRow["No_x0020_of_x0020_L1_x0020_Remin"]) >= Convert.ToInt32(maxL1Escalation) && Convert.ToDateTime(myRow["L2_x0020_Last_x0020_Escalated_x0"]) < DateTime.Now.Date.AddDays(-Convert.ToInt32(reminderinterval)))
                                          select myRow;

                            foreach (var v in results)
                            {
                                collEligible = results.CopyToDataTable<DataRow>();
                                break;
                            }
池木 2024-12-17 19:29:33

下面的代码对我有用。请尝试

 DataRow []dataRow = dataTable.Select(query, seq);
 if (dataRow != null && dataRow.Length > 0)
 {
     return dataTable.Select(query, seq).CopyToDataTable();                                            
 }  

Below code works for me. please try

 DataRow []dataRow = dataTable.Select(query, seq);
 if (dataRow != null && dataRow.Length > 0)
 {
     return dataTable.Select(query, seq).CopyToDataTable();                                            
 }  
ペ泪落弦音 2024-12-17 19:29:33

可重用的通用解决方案:

创建一个扩展方法:

public static IEnumerable<T> NullIfEmpty<T>(this IEnumerable<T> source) => source.Count() > 0 ? source : null;

现在您可以像这样调用此扩展方法:

var newTable = dataRows.NullIfEmpty()?.CopyToDataTable();
//Here dataRows can be of any IEnumerable collection such as EnumerableRowCollection<DataRow> in case of DataTable

Reusable generic solution:

Create an extension method:

public static IEnumerable<T> NullIfEmpty<T>(this IEnumerable<T> source) => source.Count() > 0 ? source : null;

Now you can call this extension method like:

var newTable = dataRows.NullIfEmpty()?.CopyToDataTable();
//Here dataRows can be of any IEnumerable collection such as EnumerableRowCollection<DataRow> in case of DataTable
倾`听者〃 2024-12-17 19:29:33

您可以使用扩展方法 Any(): 在使用 CopyToDataTable() 之前进行检查以避免 No Datarow found 异常

IEnumerable<DataRow> result = <<Some Linq Query>>;

        if (result.Any())
        {
             
        }

You can use the extension method Any(): to check before using CopyToDataTable() to avoid No Datarow found exception

IEnumerable<DataRow> result = <<Some Linq Query>>;

        if (result.Any())
        {
             
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文