【问题标题】:How to Arrange DataRow Sequences in datatable?如何在数据表中排列 DataRow 序列?
【发布时间】:2020-04-10 13:35:45
【问题描述】:
我在 DataTable 中有带有 RowsOrder 位置的列?
在 rowsorder 位置数据是-
列中的位置:
1
1a
3
4
6
7
8
9
10
11
2a
11a
12
13a
14
5
2
12b
14c
abc
我要显示位置
1
1a
2
2a
5
3
4
6
7
8
9
10
11
11a
12
12b
13a
14
14a
14c
......
..
100
100a
101b
......
1011a
【问题讨论】:
标签:
c#
.net
asp.net-mvc
datatables
【解决方案1】:
使用 IComparable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("AlphaNumeric", typeof(string));
dt.Rows.Add(new object[] { "1" });
dt.Rows.Add(new object[] { "1a" });
dt.Rows.Add(new object[] { "3" });
dt.Rows.Add(new object[] { "4" });
dt.Rows.Add(new object[] { "6" });
dt.Rows.Add(new object[] { "7" });
dt.Rows.Add(new object[] { "8" });
dt.Rows.Add(new object[] { "9" });
dt.Rows.Add(new object[] { "10" });
dt.Rows.Add(new object[] { "11" });
dt.Rows.Add(new object[] { "2a" });
dt.Rows.Add(new object[] { "11a" });
dt.Rows.Add(new object[] { "12" });
dt.Rows.Add(new object[] { "13a" });
dt.Rows.Add(new object[] { "14" });
dt.Rows.Add(new object[] { "5" });
dt.Rows.Add(new object[] { "2" });
dt.Rows.Add(new object[] { "12b" });
dt.Rows.Add(new object[] { "14c" });
dt.Rows.Add(new object[] { "abc" });
dt.Rows.Add(new object[] { "1011a" });
dt.Rows.Add(new object[] { "101b" });
dt.Rows.Add(new object[] { "100a" });
dt.Rows.Add(new object[] { "100" });
DataTable sorted = dt.AsEnumerable().OrderBy(x => new SortAlphaNumeric(x.Field<string>("AlphaNumeric"))).CopyToDataTable();
}
}
public class SortAlphaNumeric : IComparable<SortAlphaNumeric>
{
public int? number { get;set;}
public string alpha { get;set;}
public SortAlphaNumeric(string alphaNumeric)
{
string pattern = @"(?'number'\d*)(?'alpha'.*)";
Match match = Regex.Match(alphaNumeric, pattern);
string numberStr = match.Groups["number"].Value;
alpha = match.Groups["alpha"].Value;
if (numberStr.Length > 0)
{
number = (int?)int.Parse(numberStr);
}
}
public int CompareTo(SortAlphaNumeric other)
{
if (number == null)
{
if (other.number == null)
{
return alpha.CompareTo(other.alpha);
}
else
{
return 1 ; //other is greater than this
}
}
else
{
if (other.number == null)
{
return -1; //this is greater than other
}
else
{
if (this.number == other.number)
{
return this.alpha.CompareTo(other.alpha);
}
else
{
return ((int)this.number).CompareTo((int)other.number);
}
}
}
}
}
}