Anbuselvan
Anbuselvan

Reputation: 261

Extract DataTable values using Linq "C#"

I have a datatable dtRecords with values like this:

RollNo Name

120 john

121 johney

122 sam

I want to add those values in a list box like the below format.

RollNo:[RollNo] , Name: [Name]

Note : [RollNo] is ColumnName Identification Format

Expected output:

RollNo: 120 ,Name: John

RollNo: 121 ,Name: Johney

I can achieve this using a for loop but is there some other way such as using linq or any other concept.

Please include examples with your suggestions.

I tried using the linq code below but I didn't get the proper output.

string mystring="RollNo:[RollNo] , Name: [Name]";
List<DataColumn> cols = ClsGlobal.dtRecords.Columns.Cast<DataColumn>().ToList();
dtRecords.AsEnumerable().ToList().ForEach(r => cols.ForEach(c =>listBox1.Items.Add(mystring.Replace("[" + c.ColumnName + "]", r[c.ColumnName].ToString()))));

Upvotes: 2

Views: 637

Answers (1)

Icarus
Icarus

Reputation: 63956

Something like this?

var query = (from c in dt.AsEnumerable()
             select new { Value=c.Field<int>("RollNo"), 
             Text=c.Field<string>("Name")}).ToList();

And then just bind query to the ListBox.

UPDATE

OP wants just strings; so this should do it:

var query = (from c in dt.AsEnumerable()
         select "RollNo: "+ c.Field<int>("RollNo")+ " , Name: "+ c.Field<string>("Name")).ToList();

Upvotes: 3

Related Questions