如果有多个属性,如何排序列表类型的泛型? [英] How to sort list type generic if more than one property?

查看:54
本文介绍了如果有多个属性,如何排序列表类型的泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有属性(类类型)的列表泛型.我需要Z参数(TrainingSet)的排序方法:

I have a list-generic that has a property (class type). I need a sort method for Z parameters (TrainingSet):

public override List<TrainingSet> CalculatedDistancesArray
    (List<TrainigSet> ts, double x, double y, int k)
{
    for (int i =0; i < ts.Count; i++)
    {
        ts[i].Z = (Math.Sqrt(Math.Pow((ts[i].X - x), 2) 
                  + Math.Pow((ts[i].Y - y), 2)));
    }
    // I want to sort according to Z
    ts.Sort(); //Failed to compare two elements in the array.
    List<TrainingSet> sortedlist = new List<TrainingSet>();
    for (int i = 0; i < k; i++)
    {
        sortedlist.Add(ts[i]);
    }
    return ts;
}

public class TrainigSet
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Z { get; set; }
    public string Risk { get; set; }
}

推荐答案

仅对单个属性进行排序就很容易.使用需要 Comparison< T> :

Just sorting on a single property is easy. Use the overload which takes a Comparison<T>:

// C# 2
ts.Sort(delegate (TrainingSet o1, TrainingSet o2) 
       { return o1.Z.CompareTo(o2.Z)); }
);

// C# 3
ts.Sort((o1, o2) => o1.Z.CompareTo(o2.Z));

对多个属性进行排序有点棘手.我有一些类以复合方式建立比较,以及建立投影比较",但是如果您真的只想按Z排序,那么上面的代码将变得非常简单.

Sorting on multiple properties is a bit trickier. I've got classes to build up comparisons in a compound manner, as well as building "projection comparisons" but if you really only want to sort by Z then the above code is going to be as easy as it gets.

如果您使用的是.NET 3.5,并且实际上并不需要列表进行就地排序,则可以使用OrderBy和ThenBy,例如

If you're using .NET 3.5 and you don't really need the list to be sorted in-place, you can use OrderBy and ThenBy, e.g.

return ts.OrderBy(t => t.Z);

或更复杂的比较:

return ts.OrderBy(t => t.Z).ThenBy(t => t.X);

这些将由查询表达式中的 orderby 子句表示:

These would be represented by orderby clauses in a query expression:

return from t in ts
       orderby t.Z
       select t;

return from t in ts
       orderby t.Z, t.X
       select t;

(如果需要,您也可以降序排序.)

(You can also sort in a descending manner if you want.)

这篇关于如果有多个属性,如何排序列表类型的泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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