2010-06-23 5 views
2

좋아, 내가 정렬하고 싶은 목록이있다. 첫째, 일부 코드 :목록 목록을 정렬하는 방법?

foreach (var Row in Result) 
    { 
     foreach (var RowAll in Row.All) 
     { 
      DataObject.Add(new List<string>() { RowAll.Value1, RowAll.Value2, RowAll.Value3}); 
      break; 
     } 
    } 

이제 각 하위 목록의 Value2별로 정렬하려고합니다. 이것이 가능합니까? 그렇다면 어떻게해야합니까?

답변

9

당신은 LINQ를 통해이 작업을 수행 할 수 있습니다

// I'm assuming here that "LastCheckin" is defined as List<List<string>> or similar 
// ... 

var sorted = Data.LastCheckin.OrderBy(list => list[1]); 

이 하위 목록 (값 2)에서 두 번째 값으로 분류하여 "목록"을 포함하는 IEnumerable<List<string>>을 반환합니다. 당신은 장소에 목록을 정렬하려면


대신 List<T>.Sort을 사용할 수

Data.LastCheckin.Sort((a,b) => a[1].CompareTo(b[1])); 

를 지정해야하는 경우, 런타임, 오름차순 또는 분야별로, 이것이 처리 할 수있는 쉬운 방법에 :

bool ascending = true; // Set to false for decending 

int mult = ascending ? 1 : -1; 
Data.LastCheckin.Sort((a,b) => mult * a[1].CompareTo(b[1])); 

더 복잡한 검사를 처리하기 위해, 당신은 무 이상 당신의 람다를 분할 할 수 있습니다 ltiple 줄 :

bool ascending = true; // Set to false for decending 
string myDateFormat = GetDateFormat(); // Specify date format 

int mult = ascending ? 1 : -1; 
Data.LastCheckin.Sort((aStr,bStr) => 
    { 
     DateTime a, b; 
     bool aSuccess = DateTime.TryParseExact(aStr[1], myDateFormat, DateTimeStyles.None, CultureInfo.InvariantCulture, out a); 
     bool bSuccess = DateTime.TryParseExact(bStr[1], myDateFormat, DateTimeStyles.None, CultureInfo.InvariantCulture, out b); 

     int result; 
     if (!aSuccess) 
      result = bSuccess ? -1 : 0; 
     else if (!bSuccess) 
      result = 1; 
     else 
      result = a.CompareTo(b); 

     return mult * result; 

    }); 

이것은 a와 b에서 파서 오류를 처리하고 정렬의 끝에 넣어야합니다. 분류로를주지 않고

listOfLists = listOfLists.OrderByDescending(a => a.Max(x => x.paramToSoryBy)).ToList(); 
+0

가 어떻게 Data.LastCheckin의 데이터를 유지할 수 있습니다 : – sooprise

+0

@Soo : 방금 목록 을 통해이를 수행하는 적절한 정렬을 추가했습니다. 니가 한 일을해야 해. –

+0

오름차순 또는 내림차순 지정 방법은 무엇입니까? – sooprise

1

나는이 작업을 얻을 수 있었다? 또는 정렬 된 내용에 어떻게 액세스하여 Data.LastCheckin에 다시 넣을 수 있습니까?
관련 문제