user6787358 user6787358 - 3 months ago 16
C# Question

How to distinct datatable rows?

I am trying to use LINQ in my app. This is the code I used:

dataTable1.Rows.Cast<DataRow>().GroupBy(
x => x.Field<string>("item")).Where(
g => g.Count() > 1).Skip(1).SelectMany(g => g).ToList<DataRow>().ForEach(r => r.Delete());


This code is supposed to distinct the datatable rows, like distinctBy() method in more LINQ library. but it just messes up with my project. I really don't know what is wrong with it. All I need is it to remove the rows with the same column value.

What is the problem? How should I fix this?

Answer

Your Skip is skipping the first group, rather than the first item in each group.

Instead of

.Skip(1).SelectMany(g => g)

try

.SelectMany(g => g.Skip(1))
Comments