C#-使用扩展方法排序 [英] C# - Sorting using Extension Method

查看:70
本文介绍了C#-使用扩展方法排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对要说的人列表进行排序

I want to sort a list of person say

List<Person> persons=new List<Person>();
persons.Add(new Person("Jon","Bernald",45000.89));
persons.Add(new Person("Mark","Drake",346.89)); 
persons.Add(new Person("Bill","Watts",456.899));

基于

public enum CompareOptions
 {
    ByFirstName,
    ByLastName,
    BySalary
 }

 public enum SortOrder
 {
   Ascending,
   Descending
 }

使用lambda表达式进行排序的方式是什么?

using lambda expression what is the way to go for sorting?

    public static List<Person> SortPeople(this List<Person> lst, 
   CompareOptions opt1,SortOrder ord)

        {
           lst.Sort((p,op1,op2)=>{ how to apply lambda expression here});
        }

推荐答案

似乎您正在尝试在List<T>上调用采用Comparison<T>委托的Sort方法.这将需要一些工作,因为您首先必须定义一个兼容的比较功能.

It looks like you are attempting to call the Sort method on List<T> which takes a Comparison<T> delegate. This will require a bit of work because you first have to define a compatible comparison function.

第一步是根据CompareOptions值编写比较函数

First step is to write a comparison function based on the CompareOptions value

private static Comparison<Person> Create(CompareOptions opt) {
  switch (opt) {
    case CompareOptions.ByFirstName: (x,y) => x.FirstName.CompareTo(y.FirstName);
    case CompareOptions.ByLastName: (x,y) => x.LastName.CompareTo(y.LastName);
    case CompareOptions.BySalary: (x,y) => x.Salary - y.Salary;
    default: throw new Exception();
  }
}

默认情况下,此函数将按升序排序.如果您希望它下降,则只需取反值即可.因此,现在可以通过以下

By default this function will sort in ascending order. If you want it to be descending simply negate the value. So now writing SortPeople can be done by the following

public static List<Person> SortPeople(
   this List<Person> list, 
   CompareOptions opt1,
   SortOrder ord) )
   var original = Create(opt1);
   var comp = original;
   if( ord == SortOrder.Descending ) {
     comp = (x,y) => -(orig(x,y));
   }
   list.Sort(comp);
}

编辑

以lambda格式100%完成的版本

Version which is done 100% in a lambda

public static List<Person> SortPeople(
   this List<Person> list, 
   CompareOptions opt1,
   SortOrder ord) )

   list.Sort( (x,y) => {
     int comp = 0;
     switch (opt) {
       case CompareOptions.ByFirstName: comp = x.FirstName.CompareTo(y.FirstName);
       case CompareOptions.ByLastName: comp = x.LastName.CompareTo(y.LastName);
       case CompareOptions.BySalary: comp = x.Salary.CompareTo(y.Salary);
       default: throw new Exception();
     }
     if ( ord == SortOrder.Descending ) {
       comp = -comp;
     }
     return comp;
   });
}

这篇关于C#-使用扩展方法排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆