按姓氏和名字排序c#

时间:2014-01-24 10:31:12

标签: c# string sorting

这是另一项功课。我需要按照它的姓氏和名字(首先是姓氏和第二个名字)对学生进行排序。完整的学生名单必须按字母顺序编辑。

到目前为止有效:

如果我输入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”类型异常

其他信息:索引超出了数组的范围。

5 个答案:

答案 0 :(得分:1)

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));
        }
    }

答案 1 :(得分:1)

您需要检查您正在访问的阵列的长度。如果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]) ) )

答案 2 :(得分:0)

using System.Linq;

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

答案 3 :(得分:0)

只是在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 

答案 4 :(得分:0)

您可以使用IComparer界面指定对象的顺序。

这是我在LinqPad中废弃的代码(使用 @Serv 提供的名称 - 是的,我 lazy ...)

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方法使用的排序算法,否则上面的代码就足够了。

以下是结果:

Results.