I have this Linq expression that works well. What is the right approach to test if it has returned anything?

        internal static void getCreditNotes(string invoiceId, out DataTable creditNotes,out double total)
        {
            total = 0;
            creditNotes = new DataTable();
            var q = dt.AsEnumerable().
                Where(r => 
                    (string) r["invoiceId"] == invoiceId 
                    && (string) r["TransactionType"] == "CreditMemo");
            creditNotes = q.CopyToDataTable();         
            total = creditNotes.AsEnumerable().Sum(r => (double) r["TransactionAmount"]);

This code breaks on line 9 (q.CopyToDataTables) when there are no rows. I could use a try catch but that seems a bit of an overkill.

Recommended Answers

All 4 Replies

Why should try-catch be an overkill? It is designed for situations like that.

Well... I'd rather check if q is empty. q being empty is not an error condition.
Thanks.

Then a simple if statement will accomplish it.

right.... That's what I was missing: if (What?). The answer is if(q.Count()==0) of course.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.