多条件排序(C# and Lua)

C#

public class Fruit
{
    public int id;
    public string name;
    public float price;
    public float weight;
}

List<Fruit> list = new List<Fruit>();
list.Add(new Fruit { id = 2, name = "苹果", price = 9.9f ,weight = 500});
list.Add(new Fruit { id = 5, name = "西瓜", price = 1.2f, weight = 5000 });
list.Add(new Fruit { id = 1, name = "草莓", price = 29.9f, weight = 80 });
list.Add(new Fruit { id = 3, name = "香蕉", price = 6f, weight = 800 });
list.Add(new Fruit { id = 4, name = "哈密瓜", price = 2.5f, weight = 3000 });

第一种

返回值

作用

大于0

升序

等于0

不变

小于0

降序

list.Sort((a, b) =>
  {
    if (a.id != b.id)
      {
        // return a.id - b.id;//升序
        return b.id - a.id;//降序
      }
    else
      {
        if (a.price != b.price)
          {
            return a.price > b.price ? 1 : 0;
          }
        else
          {
            return (int)(a.weight - b.weight);
          }
        }
      });

第二种

升序排序

OrderBy

按升序对序列的元素进行排序

ThenBy

按升序对序列中的元素执行后续排序

降序排序

OrderByDescending

按降序对序列的元素排序

ThenByDescending

按降序对序列中的元素执行后续排序

升序排序

IOrderedEnumerable<Fruit> result = list.OrderBy(x => x.id)
    .ThenBy(x=>x.price)
    .ThenBy(x=>x.weight);

降序排序

IOrderedEnumerable<Fruit> result = list.OrderByDescending(x => x.id)
    .ThenByDescending(x=>x.price)
    .ThenByDescending(x=>x.weight);

Lua

local list = {
  [1] = {id = 101,name = "小明",age = 16,score = 88};
  [2] = {id = 103,name = "小红",age = 15,score = 91};
  [3] = {id = 107,name = "小刚",age = 16,score = 81};
  [4] = {id = 105,name = "小丽",age = 15,score = 91};
  [5] = {id = 104,name = "小龙",age = 14,score = 88};
}


table.sort(list,function(a,b)
    if a.score == b.score then
      if a.age == b.age then
        return a.id > b.id
      else
        return a.age > b.age
      end  
    else
      return a.score > b.score
    end  
  end)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值