C# 作为字符串的OrderBy编号(无法转换为int)

C# 作为字符串的OrderBy编号(无法转换为int),c#,.net,string,linq,list,C#,.net,String,Linq,List,我试图对一个列表进行排序,该列表包含一个元素列表,每个元素后面都是数字和字母。这就是为什么不能简单地将每个元素转换为int。该列表在运行时生成,但例如,该列表可能包含以下元素: 10 dog, 53 cow, 2 crow, 29 horse, 12 rabbit, 107 frog, 35 cat, 7 dragon 我试过这样分类: public void Compare() { sortedList = sortedList.OrderBy(g => g).ToList

我试图对一个
列表进行排序,该列表包含一个元素列表,每个元素后面都是数字和字母。这就是为什么不能简单地将每个元素转换为int。该列表在运行时生成,但例如,该列表可能包含以下元素:

10 dog, 53 cow, 2 crow, 29 horse, 12 rabbit, 107 frog, 35 cat, 7 dragon
我试过这样分类:

public void Compare()
{   
   sortedList = sortedList.OrderBy(g => g).ToList(); 
}
结果:

10 dog, 107 frog, 12 rabbit, 2 crow, 29 horse, 35 cat, 53 cow, 7 dragon
很明显,它是按字母顺序排序的,因为在这个例子中,107排在12之前,而107中的“10”小于12。但是我需要对它进行排序,使它能够按照单词前面的数字顺序返回

我需要这个例子来返回:

2 crow, 7 dragon, 10 dog, 12 rabbit, 29 horse, 35 cat, 53 cow, 107 frog

我对编码相当陌生,这让我完全困惑。有没有关于如何达到预期效果的建议

您可以提取所需的数据,然后通过

var sorted = list
    .Select(x => new
    {
        Splited = x.Split(),
        Raw = x
    }) //split the string and keep the raw value
    .Select(x => new
    {
        Count = int.Parse(x.Splited[0]), // extract the number 
        Raw = x.Raw
    })
    .OrderBy(x => x.Count) //order by that number
    .Select(x => x.Raw); //select raw value

正如您已经指出的,问题是您不能
OrderBy
字符串。您希望按数字部分对列表进行排序,并将其视为数字

我们将通过拆分第一个空格上的字符串,将第一个部分
parts[0]
转换为
int
并根据该值对列表排序,告诉
OrderBy
对该部分进行排序

无需使用
选择
,存储原始值等。只需在原始的
列表中添加一个简单的
OrderBy

namespace SortListTest1
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            var animals = new List<string> { "10 dog", "53 cow", "2 crow", "29 horse", "12 rabbit", "107 frog", "35 cat", "7 dragon" };

            var orderedAnimals = animals.OrderBy(
                x =>
                    {
                        var parts = x.Split(' '); // split on first space
                        return int.Parse(parts[0]); // i.e. the numeric part, cast to an int
                    });

            foreach (var orderedAnimal in orderedAnimals)
            {
                Console.WriteLine(orderedAnimal);
            }
        }
    }
}
使用以下行进行排序:
List L=新列表{“10只狗”、“53头牛”、“2只乌鸦”、“29匹马”、“12只兔子”、“107只青蛙”、“35只猫”、“7条龙”};
var sort=从L中的s开始
orderby Convert.ToInt32(s.Split(“”)[0])
选择s;

我建议不要使用字符串列表,而是使用字典。您的数据结构看起来是键值形式的

Dictionary<int,string> Animals = new Dictionary<int,string>();

使用空格作为分隔符拆分字符串,取第一个值并将其转换为in
int

sortedList = sortedList
    .OrderBy(g => Int32.Parse(g.Split(' ')[0]))
    .ToList()

我建议采取另一种方法:您有一个(
count
name
)对(或(
id
name
)对的列表,其中
name
是您的数据对象,
count
是一个量词

  • 解析数据以将其拆分为原子值(在本例中为
    int
    string
  • 将值放入适合您需要的指定结构中(这里它只是属性
    名称
  • 在适当的容器类中组装数据对象(如
    List`1
    Dictionary`2
  • 如果未排序,则对其进行排序;您可能需要让您的数据结构/类实现
    IComparable`1
    /
    IComparable
    或定义自定义的
    icomparaler`1

  • 以下是我的想法:

    代码:

    static void Main(string[] args) {
        var unsortedList = new List<string>() { "10 dog", "53 cow", "2 crow", "29 horse", "12 rabbit", "107 frog", "35 cat", "7 dragon" };
        var sortedList = new SortedList<int, string>((int)unsortedList.Count);
        foreach(var entry in unsortedList) {
            string[] frags = entry.Split(' ');
            if(frags.Length != 2) {
                throw new FormatException();
            }
            int count = Convert.ToInt32(frags[0]);
            string name = frags[1];
            sortedList.Add(count, name);
        }
        Console.WriteLine("UNSORTED:");
        unsortedList.ForEach(Console.WriteLine);
        Console.WriteLine();
    
        Console.WriteLine("SORTED:");
        foreach(var entry in sortedList) {
            Console.WriteLine(entry.Key + " " + entry.Value);
        }
        Console.WriteLine();
        Console.ReadKey();
    }
    
    static void Main(字符串[]args){
    var unsortedList=新列表(){“10只狗”、“53头牛”、“2只乌鸦”、“29匹马”、“12只兔子”、“107只青蛙”、“35只猫”、“7条龙”};
    var sortedList=新的sortedList((int)unsortedList.Count);
    foreach(未分类列表中的var条目){
    string[]frags=entry.Split(“”);
    如果(碎片长度!=2){
    抛出新的FormatException();
    }
    int count=Convert.ToInt32(frags[0]);
    字符串名称=frags[1];
    分类列表。添加(计数、名称);
    }
    Console.WriteLine(“未排序:”);
    未排序的list.ForEach(Console.WriteLine);
    Console.WriteLine();
    Console.WriteLine(“排序:”);
    foreach(分类列表中的var条目){
    Console.WriteLine(entry.Key+“”+entry.Value);
    }
    Console.WriteLine();
    Console.ReadKey();
    }
    
    输出:
    我知道这不是你要的。我也看到有很多答案可以完全按照你的要求去做这是一个建议

    我不知道您的系统或任何东西,但我认为在这里将对象作为字符串处理是一个错误。我非常肯定,您的系统可以从使用and对象而不是这个表示对象的字符串中获益。通过创建一个简单的对象,例如

    public class Animal
    {
        public string Name{ get; set }
        public int Index{ get; set; }
    }
    
    您将在许多地方获得类型安全性。它将变得更容易修改(在您当前的系统中,尝试添加第三个属性,例如Type[“哺乳动物”、“爬行动物”、“鱼”等],您将理解我所说的内容)。如果需要将该对象显示为现有字符串,则始终可以覆盖该对象的
    ToString()
    ,如所述

    现在,当您需要对对象进行排序或操作时,它会变得简单得多,因为您有一个常规对象,而不是包含对象的字符串。

    试试这个

    sortedList.OrderBy(g => int.Parse(g.Split(' ').First())).ToList();
    

    为了便于排序,您需要将数字与单词分开。这个词总是一个单词吗?如果是这样,可以按空格分割字符串。然而,如果你可以有多个单词,你需要找到一种可靠的方法来拆分它。虽然这是一个简化的例子,可以保证一个简化的解决方案,但你所寻找的通常被称为“自然排序”。已有的解决方案可以解决这个问题,还可以处理字符串中不同数量的数字、不同位置等问题@lbanezowns,你应该考虑标记被接受的答案。如果OP需要对原始列表进行排序,他应该调用<代码> Toistist并把它分配给原来的List-Valable。非常感谢你!我想这一个也给了……;)
    static void Main(string[] args) {
        var unsortedList = new List<string>() { "10 dog", "53 cow", "2 crow", "29 horse", "12 rabbit", "107 frog", "35 cat", "7 dragon" };
        var sortedList = new SortedList<int, string>((int)unsortedList.Count);
        foreach(var entry in unsortedList) {
            string[] frags = entry.Split(' ');
            if(frags.Length != 2) {
                throw new FormatException();
            }
            int count = Convert.ToInt32(frags[0]);
            string name = frags[1];
            sortedList.Add(count, name);
        }
        Console.WriteLine("UNSORTED:");
        unsortedList.ForEach(Console.WriteLine);
        Console.WriteLine();
    
        Console.WriteLine("SORTED:");
        foreach(var entry in sortedList) {
            Console.WriteLine(entry.Key + " " + entry.Value);
        }
        Console.WriteLine();
        Console.ReadKey();
    }
    
    lst = lst.OrderBy(x => Convert.ToInt32(x.Split()[0])).ToList();
    
    public class Animal
    {
        public string Name{ get; set }
        public int Index{ get; set; }
    }
    
    public override string ToString() 
    {
        return string.Format("{0} {1}", Index, Name);
    }
    
    sortedList.OrderBy(g => int.Parse(g.Split(' ').First())).ToList();