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#?
-
4You should explain your problem and describe what code you have so far. Otherwise the only answer is: **yes**. – Caspar Kleijne Sep 23 '11 at 11:33
-
@caspar i want the source code in C# for my question... – kalikoi Sep 23 '11 at 11:44
-
3For future reference: asking people to write your code for you from scratch, doesn't usually meet with a very warm reception on SO. – mikemanne Sep 23 '11 at 12:52
3 Answers
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.

- 1,835
- 1
- 12
- 21
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.

- 1
- 1

- 450,073
- 74
- 686
- 939
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);

- 357
- 2
- 14