Bilal Choudhary
Bilal Choudhary

Reputation: 69

foreach to while loop conversion in dataset asp.net

How to convert following foreach loop in while loop

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        temp_data = temp_data + ................
    }
}

Upvotes: 0

Views: 750

Answers (1)

ntohl
ntohl

Reputation: 2125

You can use the enumerators of the collections like this:

IEnumerator enum1 = ds.Tables.GetEnumerator();
while (enum1.MoveNext())
{
    IEnumerator enum2 = ((DataTable)enum1.Current).Rows.GetEnumerator();
    while (enum2.MoveNext())
    {
        temp_data = temp_data + ((DataRow)enum2.Current)[0];
    }
}

But I suggest LINQ expressions:

string temp_data = (from DataTable dataTable in ds.Tables select dataTable)
    .SelectMany(o => from DataRow dataRow in o.Rows select dataRow[0])
    .Aggregate(string.Empty, (qs, q) => qs = qs + q);

Br, Márton

Upvotes: 1

Related Questions