Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle CopyToDataTable() when no rows?

Tags:

c#

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.

Thanks in advance.

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

like image 627
user997685 Avatar asked Oct 19 '11 02:10

user997685


2 Answers

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;
like image 137
Anthony Pegram Avatar answered Sep 21 '22 02:09

Anthony Pegram


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.

like image 3
Nitin Kabra Avatar answered Sep 22 '22 02:09

Nitin Kabra