c# - 如何根据第二个参数进行排序

标签 c# arrays algorithm sorting data-structures

我必须编写一个算法来根据第二个参数对名称进行排序,我无法获得逻辑如何做,输入文件将包含如下数据:

Jervie, 12, M , Jaimy ,11, F, Tony , 23, M ,Janey , 11, F

输出必须是这样的:

Jaimy, 11, F , Janey, 11, F, Jervie ,12, M, Tony , 23, M

它们根据第二个参数排序,我已经读取了这个文件并将数据存储在结构数组中:

 struct element
        {
          public    string name;              
          public int numComp;
          public string sex;
        } ;

现在我正在考虑进行排序numComp,但是如何处理算法,这是我无法理解的,有人可以帮助我吗?,如果您知道任何其他最佳解决方案,请不要犹豫,谢谢

我完成的完整代码是:

class Program
{
    struct element
    {
      public    string name;
      public string sex;
      public int numComp;
    } ;
    static void Main(string[] args)
    {

        string appRootDir = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName;
        string text = System.IO.File.ReadAllText(appRootDir+"\\File.txt");
        string[] words = text.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        int counter = 0 ,pos=0;
        element[] storage = new element[words.Count()/3];
        foreach(string str in words)
        {
            if(counter==0)
            {
                storage[pos].name = str;
                counter++;
            }
            else if (counter == 1)
            {
                storage[pos].numComp = Int32.Parse(str);
                counter++;
            }
            else if(counter==2)
            {
                storage[pos].sex = str;
                counter = 0; pos++;
            }        
        }    
      //Now how to sort on the basis of numComp and print the output as desired ?
        Console.ReadKey();
    }   

}

现在如何根据 numComp 进行排序并根据需要打印输出?

最佳答案

我假设你的意思是作为第二个参数,结果应该按 numCorp 排序,那么你为什么不使用 LINQ-Queries:

var orderedList = storage.OrderBy(i => i.numCorp);

关于c# - 如何根据第二个参数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33604206/

相关文章:

c# - WCF 自托管通过 https 连接问题

c - 段错误 malloc 指针函数

c++ - 如何复制精确的字符数c字符串

c++ - 获取UTF-8编码的std::string的实际长度?

algorithm - 整数除法性质

algorithm - 如何防止多个用户同时将项目添加到 Sharepoint 列表

c# - 在 Entity Framework 中映射/使用内置MySQL函数

c# - 我应该处理 FontFamily.Families 结果吗?

c# - 使用 Asp.Net 身份数据库第一种方法

javascript - "concat"没有将 JavaScript 数组连接在一起?