Get duplicate records for multiple columns in datatable using LINQ

In this example i am finding duplicate records from the Datatable by using Linq.

using System.Data;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var duplicates = GetTable().AsEnumerable().GroupBy(i => new
{
Name = i.Field<string>("Name"),
Subect = i.Field<string>("Subject")
}).Where(g => g.Count() > 1).Select(g => new{ g.Key.Name, g.Key.Subect}).ToList();
}
static DataTable GetTable()
{
var table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Subject", typeof(string));
table.Rows.Add("Jameel", "Maths");
table.Rows.Add("Jameel", "Maths");
table.Rows.Add("Arun", "Chemistry");
return table;
}
}
}

Enjoy programmming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s