簡體   English   中英

C#如何按姓氏而不是名字對我的名單進行排序

[英]C# how to sort my name list by the surname instead of the first name

我想按姓氏對列表進行排序,但代碼當前按名字對列表進行排序。 我已經用谷歌搜索過的大部分內容都不適用於我,因為我還沒有學會大多數這些表達方式。

我不明白如何使它按姓氏而不是名字排序。 我已經考慮過二維數組,但我不知道它們如何與排序結合使用。

using System;
using System.Collections.Generic;

namespace ConsoleApp4
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string data =
@"Max;Stroll;60
James;Parker;60
Jon;Doe;50
Bob;Dylan;40
Scott;Butler;45
";
            Console.WriteLine(sortNames(data));
        }

        private static string sortNames(string dataList)
        {
            List<string> personList = new List<string>(dataList.Trim().Split("\r\n"));
            personList.Sort();

            string addPerson = "";

            foreach (var item in personList)
            {
                addPerson += item + "\r\n";
            }
            return addPerson;
        }
    }
}

我認為您不熟悉類和 OOP 原則,而不是對所有內容都使用字符串,所以讓我們考慮一個基本的解決方案,我們只需要手動完成即可

1-我們需要您將每一行添加到 personList 的想法

2-創建另一個與personList中的行索引連接的姓氏列表,以便能夠檢索整個行,而不僅僅是姓氏

3-對姓氏列表進行排序。

4-對排序后的姓氏進行循環,並拆分每個項目以檢索姓氏在原始列表中的索引

5-使用personList中的這個索引來檢索整個人的數據,然后顯示出來。

private static string sortNames(string dataList)
{
     List<string> personList = new List<string>(dataList.Trim().Split("\r\n"));
     List<string> surnameList = new List<string>();

     for (int i=0; i<personList.Count; i++)
     {
         string[] personData = personList[i].Split(";"); //surname is located at index = 1
         string surnameAndIndex = personData[1] + " " + i.ToString(); // Stroll 0
         surnameList.Add(surnameAndIndex);
     }

     surnameList.Sort();
     string addPerson = "";
     foreach (var item in surnameList)
     {
          string[] s = item.Split(" "); //index is located at 1 in the personList
          int index = Int32.Parse(s[1]); // converts string to int
          addPerson += personList[index] + "\r\n";
     }
     return addPerson;
}

只是要記錄一下,這根本不是滿足這種需求的最佳實踐,但它是一個可以嘗試使用更多數據結構和面向對象編程的解決方案。

為此創建一個 Person 類而不是字符串。

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

或使用構造函數

public class Person
{
    public Person(string firstName, string lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }

    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    public int Age { get; private set; }
}

然后您可以將此字符串排序到 Person 類中(在這種情況下,我將 Person 類與構造函數一起使用)

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp4
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string data =
@"Max;Stroll;60
James;Parker;60
Jon;Doe;50
Bob;Dylan;40
Scott;Butler;45
";
            Person[] persons = CreatePersons(data).OrderBy(x => x.LastName); //Create a person array and then sort it by LastName

            foreach (var person in persons) //Iterate throught the sorted person array
            {
                Console.WriteLine($"{person.FirstName} {person.LastName}, {person.Age}"); //Print out every person
            }
        }

        private static Person[] CreatePersons(string dataList) //Returns a Person array
        {
            string[] splittedData = dataList.Trim().Split("\r\n"); //Splits the string list by line breaks
    
            var persons = new List<Person>(); //Creates a new List of Persons
            for (int i = 0; i < splittedData.Length; i++) //Iterate throught the splitted data
            {
                string[] splittedPerson = splittedData[i].Split(';'); //Splits the data again to get the firstname, lastname, and age
                persons.Add(new Person(splittedPerson[0], splittedPerson[1], int.Parse(splittedPerson[2]); //Create and add the person to the list
            }

            return persons.ToArray(); //Convert the list to an array and return it
        }
    }

    public class Person
    {
        public Person(string firstName, string lastName, int age)
        {
            FirstName = firstName;
            LastName = lastName;
            Age = age;
        }

        public string FirstName { get; private set; }
        public string LastName { get; private set; }
        public int Age { get; private set; }
    }
}

取而代之personList.Sort(); 用這個

personList = personList.OrderBy(x => x.Substring(x.IndexOf(';') + 1)).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM