簡體   English   中英

按姓氏和名字c#排序

[英]Sorting by last name and first name c#

這是這里的另一項作業。 我需要按姓氏和名字(首先是姓氏,其次是名字)對學生進行排序。 學生的完整列表必須按字母順序進行編輯。

到目前為止有效:

如果我輸入3個具有相同姓氏的學生,則排序正確。

可以說

理查森·馬克·理查森·邁克·理查森·馬特

正確的排序順序為:

理查森·馬克·理查森·馬特·理查森·麥克

當姓氏以相同字母開頭並且看起來相似時,它也可以工作

可以說

理查森·馬克·里士滿·盧克·里卡德·馬特

排序為

理查森·馬克·里士滿·盧克·里卡德·馬特

我的問題

該代碼不會對3個完全不同的姓氏(例如Richardson,Markson,Bekhs)進行排序...

請注意,僅允許基本功能,並且必須像下面這樣編程!

private static void sortAlpphabetical(Student[] studentList)
{
    for (int i = 1; i < studentList.Length; i++)
    {
        for (int j = 0; j < studentList.Length - 1; j++)
        {
            string lastName1 = studentList[j].lastName.ToLower() + studentList[j].name.ToLower();
            string lastName2 = studentList[j + 1].lastName.ToLower() + studentList[j + 1].name.ToLower();
            for (int k = 0; k < lastName1.Length; k++)
            {
                if (returnIndex(lastName2[k]) > returnIndex(lastName1[k]))
                {
                    Student currentStudent = studentList[j];
                    studentList[j] = studentList[j + 1];
                    studentList[j + 1] = currentStudent;
                }
            }
        }
    }
    Console.WriteLine("List of students:\n");
    for (int i = 0; i < studentList.Length; i++)
    {
        Console.WriteLine("//code");
    }
}

當我嘗試對3個不同的姓氏進行排序時,它給我的索引超出了數組的范圍。 錯誤

work.exe中發生了'System.IndexOutOfRangeException'類型的未處理異常

附加信息:索引超出了數組的范圍。

這里的k假設lastName1比lastName2長

for (int k = 0; k < lastName1.Length; k++)
{
    if (returnIndex(lastName2[k]) > returnIndex(lastName1[k]))
    {
        Student currentStudent = studentList[j];
        studentList[j] = studentList[j + 1];
        studentList[j + 1] = currentStudent;
    }
}

這樣可以防止循環檢查的長度超過較短的長度,從而防止這種情況的發生。

int shortestNameLength = Math.Min(lastName1.Length, lastName2.Length);
for (int k = 0; k < shortestNameLength ; k++)

經過一些測試后,您的算法還有另一個問題。 它將繼續與名稱中的最后一個字符進行比較。 確定訂單后就必須停止

比較角色

  • 如果相同,請檢查下一個字符
  • 如果更大,則在此處進行交換。
  • 如果少於,什么也不做,在這里做。

總結一下,替換

for (int k = 0; k < lastName1.Length; k++)
{
    if (returnIndex(lastName2[k]) > returnIndex(lastName1[k]))
    {
        Student currentStudent = studentList[j];
        studentList[j] = studentList[j + 1];
        studentList[j + 1] = currentStudent;
    }
}

int shortestNameLength = Math.Min(lastName1.Length, lastName2.Length);
for (int k = 0; k < shortestNameLength ; k++)
{
    int c1 = returnIndex(lastName1[k]);
    int c2 = returnIndex(lastName2[k]);
    if (c1 == c2)
    {
        continue;
    }
    if (c1 > c2)
    {
        Student currentStudent = studentList[j];
        studentList[j] = studentList[j + 1];
        studentList[j + 1] = currentStudent;
    }
    break;
}

完整的方法現在看起來像這樣...

    private static void sortAlpphabetical(Student[] studentList)
    {
        for (int i = 1; i < studentList.Length; i++)
        {
            for (int j = 0; j < studentList.Length - 1; j++)
            {
                string lastName1 = studentList[j].lastName.ToLower() + studentList[j].name.ToLower();
                string lastName2 = studentList[j + 1].lastName.ToLower() + studentList[j + 1].name.ToLower();
                int shortestNameLength = Math.Min(lastName1.Length, lastName2.Length);
                for (int k = 0; k < shortestNameLength; k++)
                {
                    int c1 = returnIndex(lastName1[k]);
                    int c2 = returnIndex(lastName2[k]);
                    if (c1 == c2)
                    {
                        continue;
                    }
                    if (c1 > c2)
                    {
                        Student currentStudent = studentList[j];
                        studentList[j] = studentList[j + 1];
                        studentList[j + 1] = currentStudent;
                    }
                    break;
                }
            }
        }
        Console.WriteLine("List of students:\n");
        for (int i = 0; i < studentList.Length; i++)
        {
            Console.WriteLine(string.Format("{0} {1}", studentList[i].name, studentList[i].lastName));
        }
    }

您需要檢查正在訪問的數組的長度。 如果lastName1在偏移量k處沒有字符(即lastName1.length == k ),我們知道lastName2大於lastName1 如果lastName2在偏移量k處沒有字符(即lastName2.length <= k ),則不能大於lastName1

更改

if (returnIndex(lastName2[k]) > returnIndex(lastName1[k]))

if( lastName1.length == k ||
    ( lastName2.length > k &&
      returnIndex(lastName2[k]) > returnIndex(lastName1[k]) ) )
using System.Linq;

Student[] sorted = studentList.OrderBy(x=>x.lastName).ThenBy(x=>x.name).ToArray();

只需在LinqPad中進行此操作即可,這應該會為您提供所需的輸出,除非您應該使用for循環和經典數組。

void Main()
{
    var students = new List<student>() 
    {
      new student("Alphonso", "Zander"),
      new student("Berta", "Zander"),
      new student("Giacomo", "Zander"),
      new student("Marc", "Lastly"),
      new student("God", "Allmighty")
    };

    var sortedStudents = students.OrderBy(s => s.lastName).ThenBy(s => s.firstName).Dump();
}

// Define other methods and classes here
class student
{
    public student(string fname, string lname)
    {
     this.firstName = fname; this.lastName = lname;
    }
  public string firstName { get; set; }
  public string lastName { get; set; }
}

輸出:

firstName lastName 
God       Allmighty 
Marc      Lastly 
Alphonso  Zander 
Berta     Zander 
Giacomo   Zander 

您可以使用IComparer接口指定對象的順序。

這是我在LinqPad報廢的代碼(使用的名稱由@Serv提供-是啊,我 ...)

void Main()
{
    var students = new List<Student>()
    {
        new Student("Alphonso", "Zander"),
        new Student("Berta", "Zander"),
        new Student("Giacomo", "Zander"),
        new Student("Marc", "Lastly"),
        new Student("God", "Allmighty")
    };
    students.Sort(new StudentComparer());
    students.Dump();
}

class Student
{
    public Student(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
    public string FirstName{get;set;}
    public string LastName{get;set;}
}

class StudentComparer:IComparer<Student>
{
    public int Compare(Student a, Student b)
    {
        var lastName = a.LastName.CompareTo(b.LastName);
        if(lastName == 0)
            return a.FirstName.CompareTo(b.FirstName);
        return lastName;
    }   
}

除非您想重寫Sort方法使用的排序算法,否則上面的代碼應該足夠了。

結果如下:

結果。

暫無
暫無

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

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