Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

How to select distinct rows in a datatable in C#

- 10.03.20 | 24.03.26 - ErcanOPAK

The Scenario: You’ve loaded a massive DataTable from an Excel file, a CSV, or a legacy database. Now you realize it contains duplicate entries, and you need a unique list based on one or more columns—without writing complex foreach loops or heavy LINQ queries.

The Pro Solution: The built-in DefaultView.ToTable() method is the most efficient “one-liner” to filter unique rows directly within the ADO.NET framework.


🚀 The “One-Liner” Unique Filter

To get a new DataTable containing only unique values from a specific column, use this syntax:

// Returns a new DataTable with unique "CategoryName" values
DataTable uniqueCategories = sourceTable.DefaultView.ToTable(true, "CategoryName");

🔍 Deep Dive: Understanding the Parameters

The ToTable method is surprisingly powerful. Here is exactly what is happening under the hood:

  • First Parameter (bool isDistinct): Set this to true to act like a SQL SELECT DISTINCT. It compares the values of the columns you specify and removes duplicates.
  • Second Parameter (params string[] columnNames): This defines your “Target Schema.” Only the columns you list here will exist in the resulting DataTable.

💡 Advanced: Multi-Column Distinction

Need to find unique combinations of multiple columns? You can pass an array of column names. This is perfect for generating unique “City + Country” pairs, for example:

// Get unique combinations of both City and Country
string[] columnsToMap = { "City", "Country" };
DataTable uniqueLocations = dataTable.DefaultView.ToTable(true, columnsToMap);

💎 Pro Tip: ToTable vs. LINQ

While LINQ’s .Distinct() is popular, ToTable is often faster for raw DataTables because it operates directly on the DataView layer without the overhead of creating anonymous objects or requiring DataRowComparer.

Bonus: The resulting DataTable preserves the column data types perfectly!

Summary

Don’t over-engineer your data filtering. Use DefaultView.ToTable(true, ...) for a clean, readable, and high-performance way to handle duplicate data in your C# backend.

Related posts:

Why Async Controllers Still Block Threads

C#: Use Lambda Expressions for Concise Anonymous Functions

C#: Use Using Declarations for Automatic Disposal

Post Views: 836

Post navigation

ignoring any ‘bin’ directory on a git project
How to run code if not in Debug Mode in C#

Leave a Reply Cancel reply

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

October 2026
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Sep    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (948)
  • How to add default value for Entity Framework migrations for DateTime and Bool (938)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (836)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (624)
  • Add Constraint to SQL Table to ensure email contains @ (590)
  • Average of all values in a column that are not zero in SQL (553)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (526)
  • Find numbers with more than two decimal places in SQL (468)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps
  • Photoshop: Fix a Color Profile Mismatch That Makes Printed Output Look Nothing Like What You Saw On Screen
  • WordPress: Fix Search Results That Return Pages From a Theme You Deactivated Months Ago
  • Visual Studio: Fix a Test Project That Builds Fine Alone but Fails to Discover Any Tests After a NuGet Restore
  • ASP.NET Core: Fix a File Upload That Times Out on Slow Connections Only Because Kestrel’s Minimum Data Rate Feature Kicked In
  • JavaScript: Fix an Array Destructuring Default Value That Silently Never Applies Because null Was Passed Instead of Undefined

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (973)
  • How to make theater mode the default for Youtube (948)
  • How to add default value for Entity Framework migrations for DateTime and Bool (938)
  • Get the First and Last Word from a String or Sentence in SQL (847)
  • How to select distinct rows in a datatable in C# (836)

Recent Posts

  • CSS: Fix a prefers-color-scheme Media Query That Gets Silently Overridden by a Browser Extension’s Forced Dark Mode
  • Git: Fix a Merge Commit That Silently Drops a File Because Both Branches Deleted It Differently
  • HTML5: Fix a Native Lazy-Loading Image That Never Loads Because It Sits Inside a Hidden Tab Until the User Clicks It
  • The AI Prompt That Traces a Null Reference Exception Back to the Exact Line That First Produced the Null
  • The AI Prompt That Turns a Gym Membership Contract’s Fine Print Into a Plain-English List of Cancellation Steps

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com