【问题标题】:c# doing a custom sort on a datatablec# 对数据表进行自定义排序
【发布时间】:2014-01-17 00:37:19
【问题描述】:

我的数据表中有数据需要以这种方式在第一列上排序:

A02 BLANK0010 
D02 BLANK0007 
B04 BLANK0011 
G05 BLANK0012 
C06 BLANK0014 
E08 BLANK0013 
F10 BLANK0016 
H12 BLANK0015 
B02 G112486   
C02 G125259   
E02 G125257   
F02 G112492   
G02 G125095   
H02 G112489   
A03 G125090   
B03 G112499   
C03 G125256   
D03 G002007   
E03 G112494   
F03 G002005   
G03 G112495   
H03 G002008   
A04 G115717   

如果我进行常规排序,它会像这样排序:A02、A03、A04。但我需要 A02、B02、C02... 等

我该怎么做>?到目前为止,这是我的代码:

DataView 视图 = dt.DefaultView; view.Sort = "位置";

【问题讨论】:

  • 第一列总是一个字符后跟一个数字吗?
  • 查看我的解决方案,它会解决你的问题,如果有任何问题发表评论。

标签: c#


【解决方案1】:

您需要进行自定义排序。请参阅以下问题以获取提示:DataView.Sort - more than just asc/desc (need custom sort)

您可能希望将第一列分成两个单独的列。

【讨论】:

【解决方案2】:

可能需要重构,但可以解决问题。

//group by the rows by splitting values of column
var groupBy = table.AsEnumerable()
                .GroupBy(o => 
                    Regex.Replace(o["position"].ToString(), @"[0-9]", ""));

 var dataRows = Sort(groupBy);

这是排序方法:

//yield the first row of each group
private static IEnumerable<DataRow> Sort(IEnumerable<IGrouping<string, DataRow>> groupByCollection)
{
    //sort each character group(e.g. A,B) by integer part of their values
    var groupings =
        groupByCollection.Select(
            o =>
            new
                {
                    o.Key,
                    Value = o.OrderBy(a => Regex.Replace(a["position"].ToString(), "[a-z]", "", RegexOptions.IgnoreCase)).ToArray()
                }).ToArray();

    int i = 0, j;
    for (j = 0; j < groupings[i].Value.Length; j++,i=0)
        for (i = 0; i < groupings.Length; i++)
        {
            yield return groupings[i].Value[j];
        }
}

【讨论】:

    【解决方案3】:

    尽可能的方法:添加额外的列,第一列的第一个字母,然后按该列和第一列排序。

    【讨论】:

      【解决方案4】:

      有点原始但有效的方法(在这种情况下):

      dv.Sort = substring(field, 2, 3) + substring(field, 1, 1)

      【讨论】:

        猜你喜欢
        • 2013-03-23
        • 2017-01-16
        • 1970-01-01
        • 1970-01-01
        • 2013-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多