Pen*_*uen 6 .net c# asp.net generics
我有一个list-generic,它有一个属性(类类型).我需要一个Z参数的排序方法(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; }
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 20
只需在单个房产上进行分类就很容易.使用过载,需要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));
Run Code Online (Sandbox Code Playgroud)
对多个属性进行排序有点棘手.我已经有了以复合方式构建比较的类,以及构建"投影比较",但如果你真的只想按Z排序那么上面的代码将变得如此简单.
如果您使用的是.NET 3.5,并且您不需要将列表按原样排序,则可以使用OrderBy和ThenBy,例如
return ts.OrderBy(t => t.Z);
Run Code Online (Sandbox Code Playgroud)
或者更复杂的比较:
return ts.OrderBy(t => t.Z).ThenBy(t => t.X);
Run Code Online (Sandbox Code Playgroud)
这些将由orderby查询表达式中的子句表示:
return from t in ts
orderby t.Z
select t;
Run Code Online (Sandbox Code Playgroud)
和
return from t in ts
orderby t.Z, t.X
select t;
Run Code Online (Sandbox Code Playgroud)
(如果需要,您也可以按降序排序.)
| 归档时间: |
|
| 查看次数: |
11176 次 |
| 最近记录: |