Count from enumerable dt doesnt work

Hello,

I am having some problem with my code:
task for this function is to count how many times does a variable twinValue appear in a DataTable which consists of one column, and the variable is in fact a number (without decimals), the items in datatable are also numbers (without decimals) in general format
code is:
myDt.AsEnumerable.Where(Function (x) x(0).ToString.trim.Equals(twinValue.ToString)).Count

for some reason it most often returns count of 0 ,where in fact it is 17
i tried it on some fake data where it returned 17, so problem is complex

anyone can help?

Krzysztof

@Zdzichu_Map

String comparison is the issue. “0123” and “123” could be same when comparing integers but with String it’s different.

Check the datatype of your column and convert it to numerical if not already and then compare.

For example

' If the column is Int32:
intCount = myDt.AsEnumerable().Count(Function(r) r.Field(Of Integer)(0) = CInt(twinValue))

Remember that this will throw if the column actually contains strings or mixed types. Use only when the column type is known and consistent.

Hi @Zdzichu_Map

I would recommend you to never compare DataTable numeric columns as strings, instead always convert to numeric before comparison and make sure it is not null before comparison.

Eg :
myDt.AsEnumerable().Count(Function(x) Not IsDBNull(x(0)) AndAlso Convert.ToInt32(x(0)) = twinValue)