Introduction
This article gives an explanation about how to get distinct records from Datatable using LINQ with c# and how to remove duplicate rows from Datatable based on specified columns using LINQ as well as also show you how to fetch distinct rows from Datatable using LINQ in C# and get distinct values from the DataTable and also shows how to get distinct value using Group By, select in DataTable using C#.
Manny of developers facing this issue during the development of web/windows/mobile applications, they have data in the data table and now they want to get only distinct records from the data table and for archive, this kind of requirement some developers create own logic and they use looping functionality but looping functionality is not always the right way for processing large data and it takes some time to complete this process.
So in this article, I am going to explain how you can get distinct records from Datatable using LINQ because LINQ is easy, faster, code compressive and reliable solution compared to looping functionality such as "For loop", "For each loop" and etc.
Today, I got the same requirement to display only distinct values in the grid view, actually, I have a data table with activity logs and need to load all that records into grid view and display all the activity logs to the user, but in the data table of activity logs there are many duplicate records and as per requirement the user can see only distinct records in the data grid view. So to archive this kind of requirement I have found a reliable solution to get only distinct values from the data table of activity logs, So in this article, I will share that solution with you.
Requirement
1) Declare data table with sample duplicate records.
2) Get distinct records from Datatable using LINQ.
Implementation
So, lets we start the actual implementation and as per our requirement lets design a simple form with grid view and simple button and on click event of a button we will load data from data table to grid view.
Namespace
Before starting an actual code you have to add the following namespace in code behind.
using System.Data; using System.Linq;
After an import a required namespace you have to create the object of data table globally as I showed in the code.
DataTable dtValidate = new DataTable();
Now, after creating the object of data table you have to add required columns to declared a data table as well as also add data row with duplicate records for sample logs and assign a data source to grid view in the load event of form as I showed in the code snippet. where "dgvVerifyReport" is the name of grid view and dtValidate is the object of the data table.
C#
private void Form1_Load(object sender, EventArgs e) { try { dtValidate = null; dtValidate = new DataTable(); //add columns in datatable dtValidate.Columns.Add("STATUS", typeof(byte[])); dtValidate.Columns.Add("LOGSTEP", typeof(string)); dtValidate.Columns.Add("DETAILS", typeof(string)); //Assign datasource to gridview dgvVerifyReport.DataSource = null; dgvVerifyReport.DataSource = dtValidate; // Add 1st datarow in datatable var imageConverter = new ImageConverter(); DataRow drValidate = dtValidate.NewRow(); drValidate["STATUS"] = imageConverter.ConvertTo(Properties.Resources.success, typeof(byte[])); drValidate["LOGSTEP"] = "Token Generated Successfully."; drValidate["DETAILS"] = ""; dtValidate.Rows.Add(drValidate); drValidate = null; Application.DoEvents(); // Add 2nd datarow in datatable DataRow drValidate1 = dtValidate.NewRow(); drValidate1["STATUS"] = imageConverter.ConvertTo(Properties.Resources.success, typeof(byte[])); drValidate1["LOGSTEP"] = "Token Generated Successfully."; drValidate1["DETAILS"] = ""; dtValidate.Rows.Add(drValidate1); drValidate1 = null; Application.DoEvents(); } catch (Exception ex) { throw ex; } }
Now, when you will run your application you can see the following output in your screen as a result.
Now, On click event of the button, you have to write a code to get distinct records from the data table as I showed in the code.
C#
private void btnLoadData_Click(object sender, EventArgs e) { try { #region Write a Logs dtValidate = dtValidate.AsEnumerable() .GroupBy(r => new { LOGSTEP = r.Field<string>("LOGSTEP") }) .Select(g => g.First()) .CopyToDataTable(); dgvVerifyReport.DataSource = null; dgvVerifyReport.DataSource = dtValidate; Application.DoEvents(); #endregion } catch (Exception ex) { throw ex; } }
when you build and again run your application and click on the button "LoadData" you can see the following output in your screen as a result.
Explanation
As you can see above code and if you analyzed the code then here we used LINQ to get distinct values from the data table and here we have created a group of "LOGSTEP" using group by clause and finally select the first record from each and prepare a data table and copy this data table to our actual data table "dtValidate" using CopyToDataTable() method. This method used to takes the results of a query and copies the data into the DataTable. And finally, give data source to the grid view "dgvVerifyReport" and you can see the result as I showed above.
Output
Related articles
Read CSV File In ASP.NET With Example C# and VB.NET
Export Dataset/Datatable to CSV File Using C# and VB.NET
Convert GridView to DataTable in C# and VB.Net
ProgressBar Control in C# and VB.NET
Convert GridView to DataTable in C# and VB.Net
Convert JSON to Datatable/Dataset in Asp.Net Web Forms with Bootstrap 4
SQL Server Remove Duplicate Records From Table Using UNION And EXCEPT
Export JSON Data to Excel/CSV File using AngularJs With Bootstrap
Summary
In this article, we learned how to get distinct records from DataTable using LINQ as well as also learned use to grid view and what is the use of CopyToDataTable() method in C#.