2014-02-24 2 views
0

여기에서는 길이, 높이, 깊이 및 부피가있는 상자 목록이 작성되었습니다. 자, 볼륨에 따라 정렬 된 순서로이 상자가 필요합니다. 친절하게도 저에게 볼륨을 고려한 상자 만 정렬 할 수있는 아이디어를 알려주십시오. 나는 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); 

          } 

답변

3

이 시도 :

당신은 Linq에를 사용해야합니다.

listOfBoxes = listOfBoxes.OrderBy(x => x.volume).ToList(); 
+0

vs2008을 사용 중입니다. 여기 linq 작동하지 않습니다. 이것 이외의 해결책이 있습니까? – Manju

+0

음, 어쩌면 나만의 정렬 방법을 사용하십시오. 볼륨 만 확인 중입니다. insertSort와 비슷하지만 Box를 사용하여 만들었습니다.) –

1
List<Box> sortedList = listofboxes.OrderBy(x => x.volume); 
0

... 또는 당신은 일반 목록의 정렬 방법에 대한 인수로 대리자를 사용할 수 있습니다

listOfBoxes = listOfBoxes.OrderByDescending(p => p.volume).ToList(); 
0

을 내림차순으로 주문할 수 있습니다 또한

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 방법을 확인할 수 있습니다.

관련 문제