Icculus018
Icculus018

Reputation: 1066

Using lambda to select top 1 row returned from DataTable

I have a DataTable called currencyAmounts and using lambda, my expression was working fine until the return had more than one possibility. I am searching the DataTable for a match to my "value" variable. How can I change the following expression to just select the first row returned:

DataRow resultRow = currencyAmounts.AsEnumerable().Single(r => ((decimal)r["OriginalAmount"]) == value);

I am getting the following error when this is run:

Sequence contains more than one matching element

Upvotes: 0

Views: 3253

Answers (4)

Mel Gerats
Mel Gerats

Reputation: 2262

Single will throw an error if there are more or less than 1 element in the collection.

If you want the first, and are sure there is always at least one result, use

.Single();

If you are not sure there is always at least one result, use

.SingleOrDefault();

Upvotes: 0

DeNasti
DeNasti

Reputation: 97

You can change the "Single()" with a "First()".

That's because single (from the microsoft page) "Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence."

Upvotes: 0

Z .
Z .

Reputation: 12837

you need First instead of Single

Upvotes: 0

ilkerkaran
ilkerkaran

Reputation: 4354

The Error message explains it all actually. Single() throw exception when there are more than one matching element within the condition.(or there is no element). You should use First() or FirstOrDefault()

DataRow resultRow = currencyAmounts.AsEnumerable().FirstOrDefault(r => ((decimal)r["OriginalAmount"]) == value);

Upvotes: 2

Related Questions