Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ not executed correctly

Tags:

c#

linq

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?

like image 896
Bv202 Avatar asked Dec 04 '14 13:12

Bv202


2 Answers

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);
like image 142
Tim Schmelter Avatar answered Nov 17 '22 02:11

Tim Schmelter


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);
like image 1
Anastasia Melnikova Avatar answered Nov 17 '22 02:11

Anastasia Melnikova