List<>根据指定属性排序(实现IComparer接口)

问题:

   有一个List<CourseList> testlist,类CourseList中有CourseId, CourseName,CourseStatus,TeacherName,LevelName,StudentNumber这五个属性。现在想实现testlist的按CourseList类的各个属性排序。

 

解决办法:

 

定义各属性的枚举类型
public enum CompareType

{

    CourseId,

    CourseName,

    CourseStatus,

    TeacherName,

    LevelName,

    StudentNumber

}

 

实现IComparer接口
public class CourseListComparer:IComparer<CourseList>

{



   

    private CompareType _compareColumn;



    public CompareType CompareColumn

    {

        get { return _compareColumn; }

        set { _compareColumn = value; }

    }



    public CourseListComparer(CompareType t) {

        this._compareColumn = t;



    }



    /// <summary>

    /// compare by different property

    /// </summary>

    /// <param name="x">CourseList x</param>

    /// <param name="y">CourseList y</param>

    /// <returns>int </returns>

    public int Compare(CourseList x,CourseList y) {



       

        switch (this.CompareColumn) {

            case CompareType.CourseId:

                return x.CourseId.CompareTo(y.CourseId);

            case CompareType.CourseName:

                return x.CourseName.CompareTo(y.CourseName);

            case CompareType.CourseStatus:

                return x.CourseStatus.CompareTo(y.CourseStatus);

            case CompareType.TeacherName:

                return x.TeacherName.CompareTo(y.TeacherName);

            case CompareType.LevelName:

                return x.LevelName.CompareTo(y.LevelName);

            case CompareType.StudentNumber:

                return x.StudentNumber.CompareTo(y.StudentNumber);

            default: return x.CourseId.CompareTo(y.CourseId);



        }

    }

}
调用sort方法
CourseListComparer courselistComparer = new CourseListComparer(CompareType.CourseId);



testList.Sort(courselistComparer);

 

原因:

        C#中的List<>有两个Sort方法,一个是无参的,一个是带IComparer参的。无参的方法是按默认的比较器进行排序,有参的就要自己定义一个实现IComparer接口。

       实现ICompare接口就需要实现Compare方法。Compare方法有两个要比较的输入,根据自己定义的比较规则,返回int值,0表示相等,1表示x>y,-1表示x<y.

你可能感兴趣的:(compare)