Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
305 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...