如何按特定表单对列表进行排序?

时间:2022-02-26 20:24:49

I do have a list of string that contains

我有一个包含的字符串列表

"aa1"
"aa2"
"aa3"
"bb1"
"bb2"
"bb3"

the values can be in any form where "aa3" can be at the the bottom or any other oder

值可以是“aa3”可以位于底部或任何其他oder的任何形式

I want to sort or reorder it in the form of

我想以它的形式对它进行排序或重新排序

"aa1"
"bb1"
"aa2"
"bb2"
"aa3"
"bb3"

so how can I do that

那我怎么能这样做呢

2 个解决方案

#1


3  

The following answer uses Linq to return a sequence of strings in the required order:

以下答案使用Linq以所需顺序返回一系列字符串:

List<string> l = new List<string>
{
    "aa1",
    "aa2",
    "aa3",
    "bb1",
    "bb2",
    "bb3"
};

var result = l.OrderBy(s => s[2])
              .ThenBy(s => s.Substring(0, 2));

foreach (string str in result)
    Console.WriteLine(str);

Note that the original list stays unchanged.

请注意,原始列表保持不变。


Also you could extract these pieces of strings via an anonymous object:

您还可以通过匿名对象提取这些字符串:

var result = l.Select(s => new { Name = s.Substring(0, 2), 
                                 Num = s[2].ToString() })
                .OrderBy(o => o.Num)
                .ThenBy(o => o.Name);

foreach (var a in result)
    Console.WriteLine(a.Name + a.Num);

#2


1  

You could just use LINQ:

你可以使用LINQ:

var strings = new List<string> { "aa1", "aa2", "aa3", "bb1", "bb2", "bb3" };
var orderedStrings = strings
    .OrderBy(s => s[2])
    .ThenBy(s => s[1])
    .ThenBy(s => s[0])
    .ToList();

#1


3  

The following answer uses Linq to return a sequence of strings in the required order:

以下答案使用Linq以所需顺序返回一系列字符串:

List<string> l = new List<string>
{
    "aa1",
    "aa2",
    "aa3",
    "bb1",
    "bb2",
    "bb3"
};

var result = l.OrderBy(s => s[2])
              .ThenBy(s => s.Substring(0, 2));

foreach (string str in result)
    Console.WriteLine(str);

Note that the original list stays unchanged.

请注意,原始列表保持不变。


Also you could extract these pieces of strings via an anonymous object:

您还可以通过匿名对象提取这些字符串:

var result = l.Select(s => new { Name = s.Substring(0, 2), 
                                 Num = s[2].ToString() })
                .OrderBy(o => o.Num)
                .ThenBy(o => o.Name);

foreach (var a in result)
    Console.WriteLine(a.Name + a.Num);

#2


1  

You could just use LINQ:

你可以使用LINQ:

var strings = new List<string> { "aa1", "aa2", "aa3", "bb1", "bb2", "bb3" };
var orderedStrings = strings
    .OrderBy(s => s[2])
    .ThenBy(s => s[1])
    .ThenBy(s => s[0])
    .ToList();