开发者

c# doing a custom sort on a datatable

开发者 https://www.devze.com 2023-02-01 00:58 出处:网络
i have data in a datatable that needs to be sorted on the first column this way: A02 BLANK0010 D02 BLANK0007

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. but i need A02, B02, C02... etc

how can i do this>? here my code so far:

DataView view = dt.DefaultView; view.Sort = "position";


You'll want to do a custom sort. See the following question for hints: DataView.Sort - more than just asc/desc (need custom sort)

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


As possible way: add additional column that will first letter of first column and then sort by that column and first column.


A little primitive, but effective way (in this case):

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

0

精彩评论

暂无评论...
验证码 换一张
取 消