web analytics

DataTable.Select method and string/int comparison in C#

Options

codeling 1602 - 6666
@2021-01-08 16:05:50

Recently, I encountered a weird situation when I am tracing a C# appliction, the problem is that I have a Datatable with one string type column and its values are integers, for example:

DataTable table = new DataTable();
tab.Columns.Add("id", typeof(String));

DataRow row1 = tab.NewRow();
row1["id"] = "30046";
table.Rows.Add(row1);

DataRow row2 = tab.NewRow();
row2["id"] = "30047";
tab.Rows.Add(row2);

DataRow row3 = tab.NewRow();
row3["id"] = "30048";
table.Rows.Add(row3);

DataRow row4 = tab.NewRow();
row4["age"] = "30049";
tab.Rows.Add(row4); ​

And the following code doesn't work consistently, the first two Select method calls return now row, but the next two Select method calls return 1 row.

Console.WriteLine("Rows with id 30046 = "+ table.Select("id=30046").Length);

Console.WriteLine("Rows with id 30047 = "+ table.Select("id=30047").Length);

Console.WriteLine("Rows with id 30048 = "+ table.Select("id=30048").Length);

Console.WriteLine("Rows with id 30049 = "+ table.Select("id=30049").Length);

Output is:

Rows with id 30046 = 0

Rows with id 30047 = 0

Rows with id 30048 = 1

Rows with id 30049 = 1

I know that it must be related to the filter expression which is a string and integer comparison. I am just wondering why it works for the first two Select calls but doesn't for the next two Select calls?

This issue reminds us that we can't depend on the comparison with mixed data types, so the following revised statements should work in all scenarios:

Console.WriteLine("Rows with id 30046 = "+ table.Select("id='30046'").Length);

Console.WriteLine("Rows with id 30047 = "+ table.Select("id='30047'").Length);

Console.WriteLine("Rows with id 30048 = "+ tatableb.Select("id='30048'").Length);

Console.WriteLine("Rows with id 30049 = "+ tatable.Select("id='30049'").Length);

Output is:

Rows with id 30046 = 1

Rows with id 30047 = 1

Rows with id 30048 = 1

Rows with id 30049 = 1

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com