How I can filter a Datatable by name?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
If you are working with a .NET DataTable, filtering by name usually means selecting rows whose Name column matches a value or pattern. The two common approaches are using DataView.RowFilter for UI-friendly filtering and using LINQ when you want strongly typed code and more flexible logic.
The right choice depends on where the filtered result is going. If you want a view for binding, DataView is natural. If you want to transform or copy matching rows, LINQ is often clearer.
Filter with DataView.RowFilter
RowFilter uses an expression syntax similar to SQL WHERE, but it is not full SQL. For simple string matching, it works well.
This returns only rows where the Name column is exactly Alice.
Filter by Partial Name Match
If you need “contains” or “starts with” behavior, use LIKE.
That matches Alice and Alicia.
For a contains-style search:
This is useful for search boxes and grid filtering.
Use LINQ When You Want C# Logic
LINQ becomes more attractive when filtering rules get more complex or when you want case-insensitive comparisons without relying on expression syntax tricks.
LINQ is easier to test and refactor because it stays in normal C# rather than embedding a filter expression in a string.
Return a New DataTable After Filtering
If another API expects a DataTable, you can copy the filtered rows back into one.
That gives you the same schema with only matching rows. It is a common pattern when exporting or handing data to reporting code.
Choose Based on the Output You Need
A simple rule:
- use
DataView.RowFilterfor display and binding scenarios - use LINQ for application logic and reusable filtering rules
Both are valid. The mistake is forcing one style everywhere even when the output need is different.
Another practical difference is debuggability. LINQ conditions can be stepped through in a debugger like normal C# code, while a malformed RowFilter expression often fails at runtime with a less obvious message.
Common Pitfalls
- Writing SQL syntax into
RowFilterand expecting the full SQL language to work. - Forgetting to escape quotes when the search value comes from user input.
- Assuming
RowFilteris automatically case-insensitive across all environments and data settings. - Calling
CopyToDataTable()on an empty LINQ result without handling that case first. - Using string-based filter expressions for complex business logic that would be clearer in LINQ.
Summary
- In
.NET, filter aDataTableby name with eitherDataView.RowFilteror LINQ. - '
RowFilteris good for exact matches andLIKEpatterns in UI-oriented code.' - LINQ is better when the logic is more complex or should stay in normal C#.
- Use
CopyToDataTable()only after checking that the filtered sequence has rows. - Pick the filtering style that matches whether you need a view, a sequence, or a new table.

