sk7730
sk7730

Reputation: 736

c# Select Query to fetch datatable records

I have datatable like below.

 Name    ID
 X       101
 Y       101101
 Z       101101101
 A       101101101101
 B       101102
 C       103101
 D       103102

I want to select all the names where id starts with 101.

How can i do that in c# datatable. Can anyone please suggest me...

Upvotes: 0

Views: 1301

Answers (2)

Kaf
Kaf

Reputation: 33809

Using LINQ and assuming ID column is string type:

DataTable resultsTable = dt.AsEnumerable()
                     .Where(r => r.Field<string>("ID").StartsWith("101"))
                     .CopyToDataTable();

If ID column is int type:

DataTable resultsTable = dt.AsEnumerable()
                     .Where(r => r.Field<int>("ID").ToString().StartsWith("101"))
                     .CopyToDataTable();

If you just need list of names (Not data table):

var results = dt.AsEnumerable()
                .Where(r => r.Field<int>("ID").ToString().StartsWith("101"))
                .Select(r => r.Field<string>("Name"));

Upvotes: 2

Arun Prakash
Arun Prakash

Reputation: 890

To get all the names where id starts with 101,

you can use Datarow to filter the data

        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("Name", typeof(string)));
        dt.Columns.Add(new DataColumn("ID", typeof(string)));

        dt.Rows.Add("ARUN", "101");
        dt.Rows.Add("Prakash","1011");
        dt.Rows.Add("Sanjay", "00101");
        dt.Rows.Add("Rahul", "00000");

        DataRow[] dr = dt.Select("ID like '101*'");

Upvotes: 1

Related Questions