栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

DataView.Sort-不仅仅是asc / desc(需要自定义排序)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

DataView.Sort-不仅仅是asc / desc(需要自定义排序)

好的,我只是快速地提出了建议,并没有进行所有必要的错误处理和null检查,但是它应该给您一个想法,并且应该足以使您入门:

public static class DataTableExtensions{    public static DataView ApplySort(this DataTable table, Comparison<DataRow> comparison)    {        DataTable clone = table.Clone();        List<DataRow> rows = new List<DataRow>();        foreach (DataRow row in table.Rows)        { rows.Add(row); }        rows.Sort(comparison);        foreach (DataRow row in rows)        { clone.Rows.Add(row.ItemArray);        }        return clone.DefaultView;    }}

用法:

    DataTable table = new DataTable();    table.Columns.Add("IntValue", typeof(int));    table.Columns.Add("StringValue");    table.Rows.Add(11, "Eleven");    table.Rows.Add(14, "Fourteen");    table.Rows.Add(10, "Ten");    table.Rows.Add(12, "Twelve");    table.Rows.Add(13, "Thirteen");

//按StringValue排序:

 DataView sorted = table.ApplySort((r, r2) =>        { return ((string)r["StringValue"]).CompareTo(((string)r2["StringValue"]));        });

结果:

11点11分

14十四

10十

13十三

12十二

//按IntValue排序:

DataView sorted = table.ApplySort((r, r2) => {     return ((int)r["IntValue"]).CompareTo(((int)r2["IntValue"])); });

结果:

10十

11点11分

13十三

12十二

14十四

编辑:更改为扩展方法。

现在,在Lambda中(或您可以创建完整的比较方法),您可以执行所需的任何类型的自定义排序逻辑。请记住,-1小于,0等于,1大于。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568430.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号