简体   繁体   English

C#对数据表进行自定义排序

[英]c# doing a custom sort on a datatable

i have data in a datatable that needs to be sorted on the first column this way: 我的数据表中的数据需要以这种方式在第一列上进行排序:

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   

if i do a regular sort, it will just sort like this: A02, A03, A04. 如果我进行常规排序,它将像这样排序:A02,A03,A04。 but i need A02, B02, C02... etc 但我需要A02,B02,C02等

how can i do this>? 我该怎么做>? here my code so far: 到目前为止,这是我的代码:

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

You'll want to do a custom sort. 您将要进行自定义排序。 See the following question for hints: DataView.Sort - more than just asc/desc (need custom sort) 有关提示,请参见以下问题: DataView.Sort-不仅仅是asc / desc(需要自定义排序)

You might want to break the first column into two separate columns. 您可能希望将第一列分为两列。

Maybe need refactorings but solves the problem. 也许需要重构,但是可以解决问题。

//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);

And Here is the Sort Method: 这是排序方法:

//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];
        }
}

A little primitive, but effective way (in this case): 一种简单但有效的方法(在这种情况下):

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

可能的方法:添加其他列,该列将成为第一列的第一个字母,然后按该列和第一列进行排序。

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

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