此处,已创建具有长度,高度,深度和体积的框列表。现在,我需要根据音量按照排序顺序排列这些盒子。请告诉我如何只考虑音量来对盒子进行分类。我使用vs2008,linq不在这里工作。还有其他任何解决方案吗?
using (StreamReader sr = new StreamReader("c:/containervalues.txt"))
while ((line = sr.ReadLine()) != null)
{
// create new instance of container for each line in file
Box box = new Box();
List<Box> listofboxes = new List<Box>();
string[] Parts = line.Split(' ');
// set non-static properties of container
box.bno = Parts[0];
box.length = Convert.ToDouble(Parts[1]);
box.height = Convert.ToDouble(Parts[2]);
box.depth = Convert.ToDouble(Parts[3]);
box.volume = Convert.ToDouble(Parts[4]);
// add container to list of containers
listofboxes.Add(box);
}
答案 0 :(得分:3)
试试这个:
您需要使用Linq。
listOfBoxes = listOfBoxes.OrderBy(x => x.volume).ToList();
答案 1 :(得分:1)
List<Box> sortedList = listofboxes.OrderBy(x => x.volume);
答案 2 :(得分:0)
..或者您可以通过降序排序
listOfBoxes = listOfBoxes.OrderByDescending(p => p.volume).ToList();
答案 3 :(得分:0)
您可以使用委托作为通用列表的Sort方法的参数:
using System;
using System.Collections.Generic;
namespace sortVolumen
{
class Program
{
static void Main(string[] args)
{
List<box> BoxList = new List<box> {
new box { Width = 2, Height = 2, Depth = 2},
new box { Width = 3, Height = 3, Depth = 3},
new box { Width = 1, Height = 1, Depth = 1},
};
foreach (box myBox in BoxList)
{
Console.WriteLine(myBox.Volumen);
}
BoxList.Sort(delegate(box a, box b) { return a.Volumen < b.Volumen ? -1 : 1;});
Console.WriteLine("after comparing");
foreach (box myBox in BoxList)
{
Console.WriteLine(myBox.Volumen);
}
Console.ReadLine();
}
}
class box
{
public double Width { get; set; }
public double Height { get; set; }
public double Depth { get; set; }
public double Volumen {
get { return Width * Height * Depth; }
}
}
}
此外,您可以检查these方法以实现相同的行为。