LINQ is not running correctly

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 the test should be true, the code in the if will not be executed. I can't debug this (it just keeps working with my code).

I think that maybe something needs to be done with deferred / immediate execution, but I cannot find a solution (I already tried adding .ToList() after select ).

Any ideas?

+6
source share
2 answers

At first, I thought that Dictinct would compare by reference, since the DataRow index returns an Object instead of an int . Therefore, I suggested using the strongly typed Field extension method. But that was not the cause of your problem.

So, until you know the reason, I offer you a different (more efficient) approach to check if all IDs are unique:

 var ids = rows.Select(r => r.Field<int>("ID")); var duplicateIdChecker = new HashSet<int>(); bool isIdUnique = ids.All(duplicateIdChecker.Add); 
+4
source

I tried your code with some test data, also wrote my piece of code for the same task, everything works. Therefore, I assume that identifiers are not compared 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); 
+1
source

Source: https://habr.com/ru/post/979108/


All Articles