如何在c#win中对多个时间和特定文本进行排序。形成 [英] How to sort multiple time and on specific text in c# win. form

查看:69
本文介绍了如何在c#win中对多个时间和特定文本进行排序。形成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在c#win中对多个时间和特定文本进行排序。像我在DataTable中有这样的记录就像这样



记录

How to sort multiple time and on specific text in c# win. form like i have records in DataTable like this

Record

Id  Name
 1  5% VAT
 2  12.5% CST
 3  12.5% VAT
 4  14% VAT
 5  2% CST







想要所需结果这样




And want Desired Result like this

Id  Name
 1  5% VAT
 2  12.5% VAT
 3  14% VAT
 4  2% CST
 5  12.5% CST





[注意使用的数据库:Access(由于客户的需要,无法将其更改为SQL)

我想要对文本进行排序: -

1)对特定字符串VAT和CST进行排序

2 )正常排序在字符串上

]





在此先感谢



[edit]已添加代码块 - OriginalGriff [/ edit]



[Note : Database Used : Access (cannot change it to SQL because of client's need)
I want sorting on text :-
1) Sorting on Specific String "VAT" And "CST"
2) Normal Sorting On The String
]


Thanks In Advance

[edit]Code block added - OriginalGriff[/edit]

推荐答案

您无法对DataTable除了在DataView上使用简单比较之外:没有内置的机制唱一个自定义排序比较器。



所以:提取行,使用Linq或类似方法对它们进行排序,然后将行放回DataTable中。

这样你就可以编写一种比较方法,可以按照你需要的方式工作。





所以......一个样本:

You can't sort a DataTable except by using "simple" comparisons on the DataView: there is no built in mechanism for using a custom sort comparer.

So: extract the rows, sort them using Linq or similar, and put the rows back into the DataTable.
That way you can write a comparison method that works any way you need it to.


So...a sample:
    // Set up your sample data
    DataTable dt = new DataTable();
    dt.Columns.Add("Id");
    dt.Columns.Add("Name");
    dt.Rows.Add(1, "5% VAT");
    dt.Rows.Add(2, "12.5% CST");
    dt.Rows.Add(3, "12.5% VAT");
    dt.Rows.Add(4, "14% VAT");
    dt.Rows.Add(5, "2% CST");
    // Extract data to Enumerable
    List<string> list = new List<string>();
    foreach (DataRow row in dt.Rows)
        {
        list.Add((string)row["name"]);
        }
    // Order list
    list = list.OrderBy(s => s, new PercentageComparer()).ToList();
    // Put sorted data back in table
    for (int i = 0; i < dt.Rows.Count; i++)
        {
        dt.Rows[i][1] = list[i];
        }
    // And display
    myDataGridView.DataSource = dt;
    }


public class PercentageComparer : IComparer<string>
    {
    public int Compare(string x, string y)
        {
        string[] partsX = x.Split(' ');
        string[] partsY = y.Split(' ');
        if (partsX[1] == partsY[1])
            {
            // Same subgroup.
            // Return based on percentage
            double dx = double.Parse(partsX[0].Trim('%'));
            double dy = double.Parse(partsY[0].Trim('%'));
            if (dx < dy) return -1;
            if (dx > dy) return 1;
            return 0;
            }
        // Return based on subgroup
        // Note order of compare: VAT before CST...
        return string.Compare(partsY[1], partsX[1]);
        }
    }


这篇关于如何在c#win中对多个时间和特定文本进行排序。形成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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