C# 在列表上实现排序算法

C# 在列表上实现排序算法,c#,algorithm,list,sorting,linq,C#,Algorithm,List,Sorting,Linq,我在CustomDataList类中创建了一些排序算法: public void SortStudents() //sorts students alphabetically { string temp; for (int i = 0; i < students.Count; i++) { for (int j = i + 1; j < students.Count; j++) {

我在CustomDataList类中创建了一些排序算法:

public void SortStudents() //sorts students alphabetically
    {
        string temp;
        for (int i = 0; i < students.Count; i++)
        {
            for (int j = i + 1; j < students.Count; j++)
            {
                if (string.Compare(students[i], students[j]) > 0)
                {
                    temp = students[j];
                    students[j] = students[i];
                    students[i] = temp;
                }
            }
            Console.WriteLine(students[i]);
        }
    }


    public string GetMaxElement()
    {
        string tempMax = null;
        foreach (string element in students)
        {
            if (tempMax == null || string.Compare(tempMax, element) > 0)
            {
                tempMax = element;
            }
        }
        return tempMax;
    }

    public string GetMinElement()
    {
        string tempMin = null;
        foreach (string element in students)
        {
            if (tempMin == null || string.Compare(tempMin, element) < 0)
            {
                tempMin = element;
            }
        }
        return tempMin;
    }
}
这段代码运行良好,但现在我需要添加其他排序算法,例如,基于名称长度对列表进行排序的算法,类似于SortStudents方法,而不使用.sort方法


如果您能建议其他类型的排序和一些关于如何创建排序算法的提示,我将不胜感激

如果您没有义务使用常规数组操作,我建议您使用

和按名称排序

var result = customDataList.OrderBy(x => x);
如果需要使用数组排序算法,请替换

if (string.Compare(students[i], students[j]) > 0)

您可以使用IComparer接口

public void SortStudents(IComparer<string> comparer) // sort students using bubble sort
{
    string temp;
    for (int i = 0; i < students.Count; i++)
    {
        for (int j = i + 1; j < students.Count; j++)
        {
            if (comparer.Compare(students[i], students[j]) > 0) // use given comparer instead.
            {
                temp = students[j];
                students[j] = students[i];
                students[i] = temp;
            }
        }
        Console.WriteLine(students[i]);
    }
}
有点像

//sorts students alphabetically
customDataList.SortStudents(Comparer<string>.Create((a, b) => string.Compare(a, b)));

//sorts students by length
customDataList.SortStudents(Comparer<string>.Create((a, b) => a.Length.CompareTo(b.Length)));
基本上,您使用的是相同的排序算法、相同的代码,但IComparer接口提供的比较逻辑不同


这种技术称为依赖项注入。在本例中,是一种方法注入类型。

您可以使其更面向对象。像这样声明一个学生类:

public class Student : IComparable<Student>
{
    public int ID {get;set;}
    public string Name {get;set;}

    public int CompareTo(Student other)
    {
        return string.Compare(Name, other.Name);
    }
}

< P>如果您构建了一个坚实的企业应用程序,并且想要支持许多类型的对象/排序算法/比较逻辑,那么您需要考虑其他的答案,建议适当的面向对象的可比较的。您可能还希望将排序算法包装到一个抽象接口中

然而,如果您只是在试验,从一个角度来看,有一种更实用的方法来实现它,对于某些开发人员来说,它可能看起来更自然,例如JavaScript开发人员

可以将Func作为高阶函数传递,该函数将负责比较对象的逻辑。它要短得多,允许您将排序算法与任何类型的比较逻辑一起重用,而无需实现庞大的合成比较器类

public void SortStudents(Func<string, string, int> compareFunction) 
{
    string temp;
    for (int i = 0; i < students.Count; i++)
    {
        for (int j = i + 1; j < students.Count; j++)
        {
            if (compareFunction(students[i], students[j]) > 0)
            {
                temp = students[j];
                students[j] = students[i];
                students[i] = temp;
            }
        }
        Console.WriteLine(students[i]);
    }
}

SortStudents(string.Compare); // sorts students alphabetically
SortStudents((a, b) => a.Length.CompareTo(b.Length)); // sorts students by the length of their names

您可以实现IComparer和IComparable接口。此外,还可以尝试使用多种方法实现接口。。。你到底在问什么?多重排序算法?每门课程的核心是什么?你可以在这里看到很多:@Gauravsa我想这就是我需要的,因为我被要求实现用户友好的界面。我试过一些方法,但都没用。你能举个例子吗?这对我来说真的很重要,现在我需要创建一些类似于SortStudents排序算法的东西。一开始,我用.Sort方法创建了排序算法,据说我是按照现在的方式创建代码的。你能解释一下Func compareFunction是什么意思吗?或者为什么是string,string,int?@Ada您可能想了解的一些东西是泛型、委托和lambda函数,它们是匿名方法的继承者。@M.kazemAkhgary您能提供任何链接吗?@Ada个人我谷歌或观看youtube视频。只要用这些关键词搜索c,它就会把你带到那里。我还没有深入购买乔恩·斯基特的书C,但我认为它值得购买。祝你好运@卡泽马卡里先生谢谢你@Ada你是对的,它是BubbleSort而不是选择排序。我的错。
//sorts students alphabetically
customDataList.SortStudents(Comparer<string>.Create((a, b) => string.Compare(a, b)));

//sorts students by length
customDataList.SortStudents(Comparer<string>.Create((a, b) => a.Length.CompareTo(b.Length)));
public class Student : IComparable<Student>
{
    public int ID {get;set;}
    public string Name {get;set;}

    public int CompareTo(Student other)
    {
        return string.Compare(Name, other.Name);
    }
}
List<Student> customDataList = new List<Student>();

customDataList.AddStudent("Jenny");
customDataList.AddStudent("Loren");
customDataList.AddStudent("Martin");
customDataList.AddStudent("Hannah");
customDataList.AddStudent("Joules");
customDataList.AddStudent("Daniel");
customDataList.AddStudent("Andy");
customDataList.AddStudent("Emilio");
customDataList.AddStudent("Ariana");
customDataList.AddStudent("Nikkita");

customDataList.Sort();  // sorts by name. default sorting
public class NameLengthComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're
                // equal. 
                return 0;
            }
            else
            {
                // If x is null and y is not null, y
                // is greater. 
                return -1;
            }
        }
        else
        {
            // If x is not null...
            //
            if (y == null)
                // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                // ...and y is not null, compare the 
                // lengths of the two strings.
                //
                int retval = x.Length.CompareTo(y.Length);

                if (retval != 0)
                {
                    // If the strings are not of equal length,
                    // the longer string is greater.
                    //
                    return retval;
                }
                else
                {
                    // If the strings are of equal length,
                    // sort them with ordinary string comparison.
                    //
                    return x.CompareTo(y);
                }
            }
        }
    }
}
NameLengthComparer nc = new NameLengthComparer();
customDataList.Sort(nc);  // sorts by length of Name
public void SortStudents(Func<string, string, int> compareFunction) 
{
    string temp;
    for (int i = 0; i < students.Count; i++)
    {
        for (int j = i + 1; j < students.Count; j++)
        {
            if (compareFunction(students[i], students[j]) > 0)
            {
                temp = students[j];
                students[j] = students[i];
                students[i] = temp;
            }
        }
        Console.WriteLine(students[i]);
    }
}

SortStudents(string.Compare); // sorts students alphabetically
SortStudents((a, b) => a.Length.CompareTo(b.Length)); // sorts students by the length of their names
public string GetMaxElement(Func<string, string, int> compareFunction)   
{
    string tempMax = null;

    foreach (string element in students)
    {
        if (tempMax == null || compareFunction(tempMax, element) > 0)
        {
            tempMax = element;
        }
    }

    return tempMax;
}