Brian Webster
Brian Webster

Reputation: 30855

.NET - Can I use SQL code on an existing Datatable?

I'd like to utilize Select & Insert statements on a DataTable in VB.NET or C#.

Example:

Dim Results as DataTable 
Results = Select * from SourceDataTable where PlayerID < 10

Is anything similar to this possible?

Thanks

Upvotes: 0

Views: 172

Answers (3)

aaron
aaron

Reputation: 748

DataTables have a select method which return an array of DataRow

the filterExpression and sort paramaters take sql;

result = SourceDataTable.Select(" PlayerID < 10 ")

Upvotes: 2

anishMarokey
anishMarokey

Reputation: 11397

For select use

DataTable dt ;
dt = dt.Select("PlayerID < 10");

in C#

Upvotes: 1

Dean Harding
Dean Harding

Reputation: 72658

If you're using .NET 3.5 then you can use LINQ (I don't know the VB.NET syntax, so here's C#):

var results = from row in SourceDataTable.AsEnumerable()
              where row.Field<int>("PlayerID") < 10
              select row;

It's not exactly the same, but certainly pretty close to "natural" SQL syntax. LINQ also has the advantage that it works on any collection type (and even directly against the database, using LINQ-to-SQL), not just DataTables.

Upvotes: 5

Related Questions