简体   繁体   English

以相反顺序循环数据集

[英]Looping dataset in reverse order

I have a dataset with say 1 to 'n' number of DataTables in it and I want to loop it but in the reverse order ie, from DataTable n to DataTable 1 . 我有一个数据集,其中有说1到'n'个数据表,我想循环它,但顺序相反,即from DataTable n to DataTable 1 Can anyone suggest me a way to do this. 谁能建议我这样做的方法。 I found some solutions but all are for sorting DataTables not Datasets. 我找到了一些解决方案,但所有解决方案都是用于对DataTables而非Dataset进行排序的。

DataSet _ds = new DataSet();
foreach (DataTable table in _ds.Tables)
{

}

You could use LINQ, you need to cast it because DataTableCollection doesn't implement IEnumerable<DataTable> but only the non-generic IEnumerable interface: 您可以使用LINQ,需要进行强制转换,因为DataTableCollection不实现IEnumerable<DataTable>而仅实现非通用IEnumerable接口:

var reversedTables = _ds.Tables.Cast<DataTable>().Reverse();
foreach(DataTable table in reversedTables)
{
    // ...
}

or with a plain for -loop: 或使用普通for -loop:

for (int i = _ds.Tables.Count - 1; i >= 0; i--)
{
    DataTable table = _ds.Tables[i];
     // ...
}

you can use a for-loop instead: 您可以使用for-loop代替:

DataSet _ds = new DataSet();
for (int i=_ds.Tables.Count-1; i>=0; i--)
{
   DataTable table = _ds.Tables[i];
}

or even simpler by decrement i within the array indexer accessor : 甚至通过减少数组索引器访问器中的 i简化:

DataSet _ds = new DataSet();
for (int i=_ds.Tables.Count-1; i>=0; )
{
   DataTable table = _ds.Tables[i--];
}

or by using a while-loop doing the same: 或使用while循环执行相同的操作:

int i=_ds.Tables.Count;
while (i>=0)
{
    DataTable table = _ds.Tables[i--];
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM