2016-06-15 1 views
0

다음은 임의의 단어 또는 필드 (LINQ) (C#)로 텍스트 데이터 정렬 또는 필터링에 대한 msdn 문서의 예제입니다. 같은 일을하고 싶지만 텍스트 파일은 .csv 파일이 아니며 구분 기호로 쉼표가 없으므로 필드/열의 시작 및 끝 위치를 지정해야합니다.시작 및 끝 열 위치를 사용하여 LINQ를 사용하여 열별로 텍스트 파일을 정렬하는 방법

public class SortLines 
    { 
     static void Main() 
     { 
      // Create an IEnumerable data source 
      string[] scores = System.IO.File.ReadAllLines(@"../../../scores.csv"); 

      // Change this to any value from 0 to 4. 
      int sortField = 1; 

      Console.WriteLine("Sorted highest to lowest by field [{0}]:", sortField); 

      // Demonstrates how to return query from a method. 
      // The query is executed here. 
      foreach (string str in RunQuery(scores, sortField)) 
      { 
       Console.WriteLine(str); 
      } 

      // Keep the console window open in debug mode. 
      Console.WriteLine("Press any key to exit"); 
      Console.ReadKey(); 
     } 

     // Returns the query variable, not query results! 
     static IEnumerable<string> RunQuery(IEnumerable<string> source, int num) 
     { 
      // Split the string and sort on field[num] 
      var scoreQuery = from line in source 
          let fields = line.Split(',') 
          orderby fields[num] descending 
          select line; 

      return scoreQuery; 
     } 
    } 

/* Output (if sortField == 1): 
    Sorted highest to lowest by field [1]: 
    116, 99, 86, 90, 94 
    120, 99, 82, 81, 79 
    111, 97, 92, 81, 60 
    114, 97, 89, 85, 82 
    121, 96, 85, 91, 60 
    122, 94, 92, 91, 91 
    117, 93, 92, 80, 87 
    118, 92, 90, 83, 78 
    113, 88, 94, 65, 91 
    112, 75, 84, 91, 39 
    119, 68, 79, 88, 92 
    115, 35, 72, 91, 70 
*/ 

텍스트 파일에 구분 기호가없는 경우 어떻게 위의 예를 정렬합니까? 예를 들어 위의 예제에서 첫 번째 줄의 쉼표 구분 기호를 모두 제거하면 11699869094 이므로 점수 열은 시작 위치 3과 끝 위치 4에 있으며 값 99가됩니다. 정렬 할 필드/열의 최종 위치입니다.

답변

1

주문 조건에 string.Substring()을 사용할 수 있습니다. Linq의 람다 구문에 대해 더 잘 알고 있습니다.

var scoreQuery = source.OrderByDescending(line => line.Substring(3, 2)); 

여기서는 문자열에서 오프셋 3을 사용한다고 가정합니다. 위치 3을 원하면 4를 대신 사용하십시오 (하위 문자열은 0 기준). 2는 주문 목적으로 사용하려는 문자 수를 나타냅니다.

다음은 쿼리 구문을 사용하는 동일한 솔루션에서의 시도입니다. 약간의 수정이 필요할 수 있습니다.

 var scoreQuery = from line in source 
         orderby line.Substring(3, 2) descending 
         select line; 
+0

감사합니다. 그게 효과가 있었어! – ptn77

+0

추가 Column을 추가하려면 다음과 같이 정렬 할 수 있습니까? var scoreQuery = 소스의 행 orderby line.Substring (3, 2) 및 line.Substring (5, 2) select 선; – ptn77

+0

'var scoreQuery = 소스에서 줄부터 orderby line.Substring (3, 2) descenting, line.Substring (5, 2) 내림차순 선택 줄; '참조 http://stackoverflow.com/questions/298725/multiple-order- by-in-linq –

관련 문제