-1

Is there any way to copy the duplicate(based on one or more columns) rows in a source datatable to the destination datatable with or without LINQ in C#?

Triad sou.
  • 2,969
  • 3
  • 23
  • 27
kalikoi
  • 1
  • 3

3 Answers3

0

Write what code you have so far makes it far easier to glean intent.

If you use LINQ, you want to use the group operator, or use LINQ extensions and the GroupBy() method, although it would give you the key list.

Like:

from row in yourDataTable.AsEnumerable()
group row by new { c1 = yourDataTabe["col1"], c2 = yourDataTable["col2"], //etc, your keyed columns } into groupedRow
where groupedRow.Count() > 1
select new 
{ 
    //output whatever anonymous type information you want
}

Without LINQ just use a HashSet<T> as memory, and do a simple check, if it's in the HashSet, then you've seen it before, and then just add to your secondary table, if not, then add it to the HashSet because it's the first time you've seen this element.

Digicoder
  • 1,835
  • 1
  • 12
  • 21
0

I've asked same myself yesterday. Maybe you find following helpful even if it's VB.NET:

Dim dups = From row In source
      Group By grp = New With {Key .Value1 = CInt(row("Value1")), Key .Value2 = CInt(row("Value2"))}
      Into Group Where Group.Count > 1
      Let Text = Group.First.Item("Text")
      Select Group.First

If dups.Any Then
      Dim dest = dups.CopyToDataTable
End If

The Let-keyword is important to add the other columns to your query in order to get a new DataTable with the duplicate rows.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Hie You have to do something like this for finding duplicate records using LINQ

int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 };
var duplicates = listOfItems
.GroupBy(i => i)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
foreach (var d in duplicates)
Console.WriteLine(d);
dLcreations
  • 357
  • 2
  • 14