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)