Extracting Distinct Records from a DataTable in C#

Working with DataTables in C# is common when handling structured data in applications. But what if you need to remove duplicate rows and extract only unique records based on specific columns?

Here's a clean and elegant solution using DataView:

DataView view = new DataView(dtCountry);
DataTable distinctCountries = view.ToTable(true, "ValuePart", "TextPart");

What Does This Do?

Let’s break it down:

  • DataView view = new DataView(dtCountry);
     Creates a view from the original DataTable dtCountry.
    Think of it like a filtered or sorted lens over your data.

  • view.ToTable(true, "ValuePart", "TextPart");
     Generates a new DataTable from the view:

    • true means: "Give me only distinct rows!"

    • "ValuePart", "TextPart" are the columns to keep and check for duplicates.

Leave a Reply

Your email address will not be published. Required fields are marked *


Talk to us?

Post your blog

F.A.Q

Frequently Asked Questions