c# - 根据前缀对字符串进行排序

标签 c# .net sorting arrays

如果给定一个带有随机前缀的数组,如下所示:

DOG_BOB
CAT_ROB
DOG_DANNY
MOUSE_MICKEY
DOG_STEVE
HORSE_NEIGH
CAT_RUDE
HORSE_BOO
MOUSE_STUPID

我将如何对其进行排序,以便我有 4 个不同的数组/字符串列表?

所以最终结果会给我 4 个字符串数组或列表

DOG_BOB,DOG_DANNY,DOG_STEVE <-- Array 1
HORSE_NEIGH, HORSE_BOO <-- Array 2
MOUSE_MICKEY, MOUSE_STUPID <-- Array 3
CAT_RUDE, CAT_ROB <-- Array 4

抱歉,这些名字是我编的,哈哈

var fieldNames = typeof(animals).GetFields()
                    .Select(field => field.Name)
                    .ToList();
List<string> cats = new List<string>();
List<string> dogs = new List<string>();
List<string> mice= new List<string>();
List<string> horse = new List<string>();
foreach (var n in fieldNames)
{
    var fieldValues = typeof(animals).GetField(n).GetValue(n);"

    //Here's what i'm trying to do, with if statements
    if (n.ToString().ToLower().Contains("horse"))
    {
    }
}

所以我需要将它们拆分为字符串数组/字符串列表而不仅仅是字符串

最佳答案

string[] strings = new string[] { 
                      "DOG_BOB",
                      "CAT_ROB",
                      "DOG_DANNY",
                      "MOUSE_MICKEY",
                      "DOG_STEVE",
                      "HORSE_NEIGH",
                      "CAT_RUDE",
                      "HORSE_BOO",
                      "MOUSE_STUPID"};

string[] results = strings.GroupBy(s => s.Split('_')[0])
                          .Select(g => String.Join(",",g))
                          .ToArray();

或者像这样

List<List<string>> res = strings.ToLookup(s => s.Split('_')[0], s => s)
                                 .Select(g => g.ToList())
                                 .ToList();

关于c# - 根据前缀对字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14387679/

相关文章:

c# - 操作无法完成。该系统找不到指定的路径

c# - 将空白行插入到具有动态列的数据网格中

c# wpf 数据绑定(bind)没有发生。

.net - WPF 禁用列表框的 MouseMove 上的项目选择

c# - 小整数的文字后缀

c# - 如何使用 WinForms (.NET) 绘制圆角矩形?

php根据字符串对数组进行排序

c# - .Sort(Function(x, y) -> 当没有要排序的内容时重新排列列表(即所有排序字段具有相同的值)

c++ - 如何在整数四面体中找到具有最小可能路径的最大和?

c# - 如何确定 .NET 中的 CPU 缓存大小?