Muthu
Muthu

Reputation: 165

How to loop through datatable values without using for or foreach loop and then list values add to List?

Tables[1] having list of values.

if (ds.Tables[1].Rows.Count > 0)
{
    // How to loop through datatable values without using for or foreach loop and then list values add to List?//


   testRetrieveResponse.testList.Add();- how to add values to list 

}

Upvotes: 1

Views: 2092

Answers (2)

Adil
Adil

Reputation: 148140

You can use DataTable.AsEnumerable

List<DataRow> list = ds.Tables[1].AsEnumerable().ToList();

OR, if you want to create list of some Type then you can use Select and make objects of your type.

List<DataRow> list = ds.Tables[1].AsEnumerable()
                     .Select(a => new YourType { Prop1 = a.Field<string>("Prop1")}).ToList();

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149548

One way of doing it would be to Enumerable.Cast each element to DataRow, then project the new element type with Enumerable.Select:

var customTypes = ds.Tables[1]
                    .Rows
                    .Cast<DataRow>()
                    .Select(row => new SomeType { Id = row["Id"] })
                    .ToList();

Upvotes: 1

Related Questions