Get Distinct Records From Datatable using LINQ C#

watch_later 1/11/2023
This article gives an explanation of 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 shows 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 developers face 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 the archive, For this kind of requirement some developers create their 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.

Get Distinct Records From Datatable using LINQ C#

So in this article, I am going to explain how you can get distinct records from Datatable using LINQ because LINQ is an 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 those records into the 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 the data table with sample duplicate records. 
2) Get distinct records from Datatable using LINQ.

Implementation


So, let us start the actual implementation, and as per our requirement let's design a simple form with a grid view and a simple button, and on click event of a button we will load data from the data table to the grid view.

Namespace


Before starting an actual code you have to add the following namespace in the code behind.
using System.Data;
using System.Linq;
After an import of a required namespace, you have to create the object of the data table globally as I showed in the code. 
DataTable dtValidate = new DataTable();
Now, after creating the object of the data table you have to add the required columns to declare a data table as well as also add a data row with duplicate records for sample logs and assign a data source to the grid view in the load event of form as I showed in the code snippet. where "dgvVerifyReport" is the name of the 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 on your screen as a result.

Datatable With Duplicate Records

Now, On the 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 on your screen as a result.

Distinct Values From DataTable

Explanation


As you can see from the above code and if you analyzed the code then here we used LINQ to get distinct values from the data table and here we 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 is used to take the results of a query and copy the data into the DataTable. And finally, give the data source to the grid view "dgvVerifyReport" and you can see the result as I showed above.

Output

Remove Duplicate Records from DataTable

Summary


In this article, we learned how to get distinct records from DataTable using LINQ as well as also learned the use of the grid view and what is the use of the CopyToDataTable() method in C#.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon