C# 按降序列出排序数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17862212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:40:29  来源:igfitidea点击:

List Sorting numbers in Descending Order

c#asp.netlist

提问by Apollo

I have a List that is not sorting at all. I used the .Sort and is not working. I want the numbers to sort in Descending order. 9,6,4,3,2

我有一个根本没有排序的列表。我使用了 .Sort 并且不工作。我希望数字按降序排序。9、6、4、3、2

 List<string> tem = new List<string>();
 using (SqlConnection cs = new SqlConnection(connStr))
 {
       cs.Open();

       for (int x = 0; x < length; x++)
       {
           SqlCommand select = new SqlCommand("spTicketIssuance_GetTransactions", cs);
                select.CommandType = System.Data.CommandType.StoredProcedure;
                select.Parameters.AddWithValue("@TransDesc", TransType[x]);

            SqlDataReader dr = select.ExecuteReader();

            while (dr.Read())
            {
                tem.Add(dr["TransTime"].ToString()); //Adds all Transaction in the multiline textbox and adds them to List  TransList
            }
            dr.Close();
       }
            tem.Sort(); //NOT SORTING
            cs.Close();
        }

采纳答案by Andrew Cooper

You say you're sorting numbers, but your list contains strings. Sorting numerical values in strings will lead to all sorts of weird results if the numbers have differing numbers of digits.

您说您正在对数字进行排序,但您的列表包含字符串。如果数字具有不同的位数,则对字符串中的数值进行排序将导致各种奇怪的结果。

This is exactly the problem with the sample you gave in your comment. The string sort compares the first character (digit) and sees that 1 < 2, so it sorts 12 before 2. If you started with "2", "12", "7", you'd see it produce the same result - "12", "2", "7".

这正是您在评论中提供的样本的问题。字符串排序比较第一个字符(数字)并看到 1 < 2,因此它在 2 之前对 12 进行排序。如果您从 开始"2", "12", "7",您会看到它产生相同的结果 - "12", "2", "7"

If you're storing numeric values, use a numeric type for your list.

如果您要存储数值,请为您的列表使用数值类型。

Also, Sort()will always sort in ascending order. If you want it to produce a descending result you'd either need to Reverse()the result, or, as other answers have said, use OrderByDescending(x => x)instead of Sort(). The latter option would be more efficient.

此外,Sort()将始终按升序排序。如果您希望它产生降序结果,您要么需要Reverse()结果,要么像其他答案所说的那样,使用OrderByDescending(x => x)代替Sort(). 后一种选择会更有效。

Update

更新

I take it from your comment on @Steve's answer that the data type in the database is a character type as well?

我从你对@Steve 回答的评论中得知,数据库中的数据类型也是字符类型?

For your text box you can do something like:

对于您的文本框,您可以执行以下操作:

string[] lines = text.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
List<int> trans = lines.Select(line => Int32.Parse(line)).ToList();

The second line will blow up if the entries aren't purely numerical, though. A safer way would be something like this:

但是,如果条目不是纯粹的数字,第二行就会炸毁。更安全的方法是这样的:

IEnumerable<int?> values = lines.Select(line => 
{
    int value; 
    return Int32.TryParse(line, out value) ? (int?)value : null;
})
List<int> trans = values.Where(v => v.HasValue).Select(v => v.Value).ToList();

This will discard any lines that can't be converted to an int.

这将丢弃任何无法转换为int.

Once you've got your data in numeric format, then store it in the database that way, and the rest of your processing (sorting, etc) becomes a lot easier.

一旦您获得了数字格式的数据,然后以这种方式将其存储在数据库中,其余的处理(排序等)就会变得容易得多。

Update 2

更新 2

Like I said in my comment, the OrderByDescending()method doesn't change the list it's applied to, but essentially provides a different enumeration order over that list. If you need the results in a list just add ToList()to do that. So:

就像我在评论中所说的那样,该OrderByDescending()方法不会更改它所应用的列表,但本质上提供了对该列表的不同枚举顺序。如果您需要列表中的结果,只需添加ToList()即可。所以:

List<int> sortedTrans = transInt.OrderByDescending(x => x).ToList();

回答by Steve

You could try with

你可以试试

var ordered = tem.OrderByDescending(x => x);

However, given the fact that you add numbers as strings, you can't get a correct order if your numbers are two digits or more.

但是,考虑到您将数字添加为字符串这一事实,如果您的数字是两位或更多位,则无法获得正确的顺序。

For example

例如

List<string> tem = new List<string>() {"11", "5", "4"};
var ordered = tem.OrderByDescending(x => x);
foreach(string s in ordered)
     Console.WriteLine(s);

will give you "5", "4", "11" because the first character "5" is greater that the first character "1" in the "11" string. You could add the string with a format specifier that adds the character for zero like this

会给你“5”、“4”、“11”,因为第一个字符“5”大于“11”字符串中的第一个字符“1”。您可以使用格式说明符添加字符串,该格式说明符会像这样添加零字符

tem.Add(string.Format("{0:D3}", dr["TransTime"])); 

and have your output correctly sorted (unless you have numbers of 4 digits and more)

并正确排序您的输出(除非您有 4 位或更多的数字)

EDIT: Example using a List(Of Integer) instead of a List(Of String) and put the result in a textbox

编辑:示例使用 List(Of Integer) 而不是 List(Of String) 并将结果放入文本框中

List<int> tem = new List<int>();
using (SqlConnection cs = new SqlConnection(connStr))
{
    .....
    tem.Add(Convert.ToInt32(dr["TransTime"])); 
}

var ordered = tem.OrderByDescending(x => x).ToList();
StringBuilder sb = new StringBuilder();
ordered.ForEach(x => sb.AppendLine(x.ToString()));
textBox.Text = sb.ToString();

回答by BradW

use the

使用

list.OrderByDescending

list.OrderByDescending

Would help

有助于

回答by Roman M

var names = new List<string> { "abc", "xyz" };
var srotedDesc = names.OrderByDescending(x => x).ToList();