Reputation: 1066
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
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
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
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