在一个DataTable排序字符串项目为int使用C# [英] Sort string items in a datatable as int using c#

查看:335
本文介绍了在一个DataTable排序字符串项目为int使用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数字codeS存储在一个DataTable。当我尝试使用数据视图对它进行排序它按字符串列。什么是数据作为整数/数字排序的最简单的方法?

I have some numeric codes stored in a DataTable. When I try to sort it using DataView it sorts the column by string. What is the easiest way to sort the data as integer/number?

DataView view = dt.DefaultView();
view.Sort = "Code asc";
dt = view.ToTable();

数据在数据表:
128,123,112,12,126

Data in datatable: 128, 123, 112, 12, 126

排序后,它表明:
112,12,123,126,128

after sort it shows: 112, 12, 123, 126, 128

预期的结果:
12,112,123,126,128

expected result: 12, 112, 123, 126, 128

推荐答案

下面是工作的例子。您可以创建通过克隆其他DataTable,并更改列Int的数据类型和复制数据。

Here is working example. You can create another DataTable via Clone, and change the data type of the column to Int and copy the data.

    DataTable dt = GetTable(); // Assume this method returns the datatable from service      
    DataTable dt2 = dt.Clone();
    dt2.Columns["Code"].DataType = Type.GetType("System.Int32");

    foreach (DataRow dr in dt.Rows)
    {
        dt2.ImportRow(dr);
    }
    dt2.AcceptChanges();
    DataView dv = dt2.DefaultView;
    dv.Sort = "Code ASC";

这篇关于在一个DataTable排序字符串项目为int使用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆