I have this piece of code:
DataTable dtDataTable = …;
var rows = dtDataTable.AsEnumerable();
var test = rows.Select(x => x["id"]).Distinct().Count() != rows.Count();
if (test)
{
MessageBox.Show("test");
return false;
}
Problem: if test should be true, the code in the if
statement does not get executed. I cannot seem to debug this (it just continues running my code).
I think it may have to do something with deferred/immediate execution, but I can't find a solution (I've tried adding .ToList()
after the select
already).
Any ideas?
First i thought that Dictinct
would compare by reference since the DataRow
indexer returns an Object
instead of an int
. So i suggested to use the strongly typed Field
extension method. But that was not the reason for your issue.
So until you don't know the reason i suggest you a different (more efficient) approach to check if all ID's are unique:
var ids = rows.Select(r => r.Field<int>("ID"));
var duplicateIdChecker = new HashSet<int>();
bool isIdUnique = ids.All(duplicateIdChecker.Add);
Tried your code with some test data, also wrote my piece of code for the same task, everything is working. So I guess that Ids are not comparing correctly
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("desc");
var dr = dt.NewRow();
dr[0] = 1;
dr[1] = "prova1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 1;
dr[1] = "prova2";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 2;
dr[1] = "prova3";
dt.Rows.Add(dr);
var rows = dt.Rows.OfType<DataRow>();
var test = (rows.Select(row => row["id"]).Distinct().Count() != rows.Count());
Console.WriteLine(test);
var rows1 = dt.AsEnumerable();
test = rows.Select(x => x["id"]).Distinct().Count() != rows.Count();
Console.WriteLine(test);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With