search

C# DataTable is a central object used to access most of the objects and data related to the data table. Since the data table comprises data in huge amounts and is not in an organized format, there comes the need to apply a filter. To satisfy the filtering properties in DataTable related to C#, it is needed to get the filter to arrange and order data streamlined C# database filter.

Syntax:

There is no specific syntax for C# DataTable filter, but still, it makes use of the filter functions associated with columns which are represented as follows:

dataView.RowFilter = "s_id=180";

DataTable filter function associated with literals is represented as follows:

dataView.RowFilter = "s_name = 'anu'"

DataTable filter function associated with number values is represented as follows:

dataView.RowFilter = "dt_of_brth = 1987"

How to Filter DataTable in C#?

Filter function in C# is mostly used whenever the data and its associated operations are huge in number. If the data present in the DataTable gets increasing, then the only savior with respect to rows and columns filtering is the filter in DataTable.

Let’s check the working pattern to filter DataTable in C#:

  • Filtering DataTable in C# is not unique and different from other types of filtering technique; still, it can be achieved in varieties of ways.
  • Filtering DataTable varieties of ways include select(String) method, which selects the required row or column and then based on that applies the filter.
  • Filtering can be done using Select, Where, AND, OR, NOT logical operator and on top of it applying the value also there.
  • Data Rows and columns present in the data table also make use of the sorting method, which sorts and orders the data in an Ascending or Descending format as necessary.
  • Selecting the string as enumerable is useful while saving any object, and then applying filter and order operation based on the computation helps in providing the desired result.
  • Evaluation of DataTable with its associated string also needs to be taken care of with respect to the true or false return function.

Examples of C# DataTable Filter

Given below are the examples of C# DataTable Filter:

Example #1

This program demonstrates the filtering and fetching of row data by using select statement as filter statement as for each with AND, OR and NOT condition and returns any number greater than the mentioned number but is less than the other upper limit as shown in the output.

Code:

using System;
using System.Data;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Data.DataSetExtensions;
public class Data_tbl_Demo
{
public static void Main()
{
DataTable tbl_1 = new DataTable("Creation of Data for players");
tbl_1.Columns.Add(new DataColumn("Size_of_team", typeof(int)));
tbl_1.Columns.Add(new DataColumn("Team_work", typeof(char)));
tbl_1.Rows.Add(50, 'c');
tbl_1.Rows.Add(100, 'c');
tbl_1.Rows.Add(250, 'd');
tbl_1.Rows.Add(567, 'd');
tbl_1.Rows.Add(123, 'd');
DataRow[] rslt = tbl_1.Select("Size_of_team >= 123 AND Team_work = 'd'");
foreach (DataRow row in rslt)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
}
}

Output:

C# DataTable Filter

Example #2

This program is used to demonstrate the DataTable filtering expression, which is used to return an array of DataRow Objects after sorting in Descending order as shown in the output.

Code:

using System;
using System.Data;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Data.DataSetExtensions;
public class Data_tbl_Demo
{
public static void Main()
{
DataTable tbl2_2 = new DataTable("Orders_plcd");
tbl2_2.Columns.Add("Order_ID", typeof(Int32));
tbl2_2.Columns.Add("Order_Quantity", typeof(Int32));
tbl2_2.Columns.Add("Company_Name", typeof(string));
tbl2_2.Columns.Add("Date_on_day", typeof(DateTime));
DataRow nw_row = tbl2_2.NewRow();
nw_row["Order_ID"] = 1;
nw_row["Order_Quantity"] = 5;
nw_row["Company_Name"] = "New_Company_Nm";
nw_row["Date_on_day"] = "2014, 5, 25";
tbl2_2.Rows.Add(nw_row);
DataRow nw_row2 = tbl2_2.NewRow();
nw_row2["Order_ID"] = 2;
nw_row2["Order_Quantity"] = 6;
nw_row2["Company_Name"] = "New_Company_Nm2";
tbl2_2.Rows.Add(nw_row2);
DataRow nw_row3 = tbl2_2.NewRow();
nw_row3["Order_ID"] = 3;
nw_row3["Order_Quantity"] = 8;
nw_row3["Company_Name"] = "New_Company_Nm3";
tbl2_2.Rows.Add(nw_row3);
string exprsn = "Date_on_day = '5/25/2014' or Order_ID = 2";
string sort_Order = "Company_Name DESC";
DataRow[] sorted_Rows;
sorted_Rows = tbl2_2.Select(exprsn, sort_Order);
for (int i = 0; i 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534880154954.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="C# DataTable Filter" ></p>
<h4 id="Example">Example #3</h4>
<p>This program demonstrates the select query where the DataTable finds for the two matching rows which have dates on the more recent format and is filtered using DateTime as shown in the output.</p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">using System;
using System.Data;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Data.DataSetExtensions;
public class Using_Date_Time
{
public static void Main()
{
DataTable tbl_dt_time = new DataTable("Widgets");
tbl_dt_time.Columns.Add(new DataColumn("rw_ID", typeof(int)));
tbl_dt_time.Columns.Add(new DataColumn("Date", typeof(DateTime)));
tbl_dt_time.Rows.Add(180, new DateTime(2003, 1, 1));
tbl_dt_time.Rows.Add(123, new DateTime(2000,1, 1));
tbl_dt_time.Rows.Add(350, new DateTime(2001,1, 1));
DataRow[] filterd_result = tbl_dt_time.Select("Date > #6/1/2001#");
foreach (DataRow row in filterd_result)
{
Console.WriteLine(row["rw_ID"]);
}
}
}

Output:

C# DataTable Filter

Example #4

This program illustrates an invalid expression by selecting a value like A that does not gets evaluated to true or false and throws a nasty error which is not desired.

Code:

using System;
using System.Data;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Data.DataSetExtensions;
public class Using_Date_Time
{
public static void Main()
{
DataTable table = new DataTable();
table.Columns.Add("Anusua", typeof(int));
table.Rows.Add(1);
table.Rows.Add(2);
table.Rows.Add(3);
table.Rows.Add(4);
table.Rows.Add(5);
DataRow[] rows = table.Select("Anusua");
System.Console.WriteLine(rows.Length);
}
}

Output:

C# DataTable Filter

Note: To overcome the above situation of evaluating the data table and filtering the data table by evaluating values, involve these set of statements properly.

Statements include lines such as:

DataRow[] rows = table.Select(“Anusua > 1”);

System.Console.WriteLine(rows.Length);

The above two lines will provide the required output if executed properly by replacing the select statement as in the previous mentioned example.

The output comes out as:

C# DataTable Filter

Example #5

This program demonstrates the data table to be filtered and perform a sum operation that will reside inside the object created as a sum, and from that, the required sum is obtained and displayed as shown in the output.

Code:

using System;
using System.Data;
using System.Xml;
using System.Collections.Generic;
using System.Linq;
using System.Data.DataSetExtensions;
public class Program
{
public static void Main()
{
DataTable dt_4 = new DataTable();
dt_4.Columns.Add("emp_Id",typeof(int));
dt_4.Columns.Add("customer_Name",typeof(string));
dt_4.Columns.Add("Amount_type",typeof(decimal));
dt_4.Rows.Add(1,"A",50);
dt_4.Rows.Add(2,"b",68);
dt_4.Rows.Add(3,"c",22);
dt_4.Rows.Add(4,"d",null);
decimal dec_ml = 0;
object sum_Obj;
sum_Obj = dt_4.Compute("Sum(Amount_type)", string.Empty);
decimal total = dt_4.AsEnumerable().Where(r => !r.IsNull("Amount_type") && decimal.TryParse(r["Amount_type"].ToString(), out dec_ml)).Sum(r => dec_ml);
Console.WriteLine(sum_Obj);
Console.WriteLine(total);
}
}

Output:

C# DataTable Filter

Conclusion

DataTable in C# and in any other programming language plays a pivotal role when dealing with a huge amount of data. Filtering with respect to the database and its subsequent subset also plays an important role as a database should always be optimized and efficient in terms of fetching and retrieving data from a database.

The above is the detailed content of C# DataTable Filter. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool