2015-09-29 3 views
0

Мне нужно прочитать 2D-массив из текстового файла и отсортировать столбец в порядке возрастания.Прочитайте данные из файла и Сортируйте данные, используя C#

Моя текущая реализация:

1) Чтение данных из файла & разделить значения на основе пустого пространства 2) и начисление 3 значения столбца 3 ArrayLists

Я пытался сортирую каждый Список_массивы с Sort(). Но не смог получить требуемый результат, только сортировка положительных значений & не отрицательные значения.

Пример кода,

 ArrayList col1 = new ArrayList(); 
     ArrayList col2 = new ArrayList(); 
     ArrayList col3 = new ArrayList(); 
     using (StreamReader sr = new StreamReader(@"E:\ArrayCol1.txt")) 
     { 
      string line; 
      while ((line = sr.ReadLine()) != null) 
      { 
       string[] split = Regex.Split(line, "[ \t]"); 

       if (split.Count() == 3) 
       { 
        col1.Add(Convert.ToInt32(split[0])); 
        col2.Add(Convert.ToInt32(split[1])); 
        col3.Add(Convert.ToInt32(split[2])); 
       } 
      } 
     } 
     col1.Sort(); 
     foreach (int s in col1) 
      Console.WriteLine(s); 

Массив Textfile данных [4,3]: -

-15 -215 -1

-20 - 600 -200

10 -70 1000

ожидается выход,

10 -70 77

-15 -215 -1

-20 -600 -200

+0

Пожалуйста, покажите нам, что код, который вы реализовали! @Rao – tpsaitwal

+1

Почему вы используете ArrayLists? – CodeCaster

ответ

0

Вы пытались отладить?

Sort() выполняет сортировку по возрастанию. Я должен был использовать OrderByDescending(), чтобы сделать его нисходящим.

переписали код:

List<int> col1 = new List<int>(); 
    List<int> col2 = new List<int>(); 
    List<int> col3 = new List<int>(); 

    using (var reader = new StreamReader(@"C:\users\susingh\desktop\data.txt")) 
    { 
     string line; 
     while (true) 
     { 
      line = reader.ReadLine(); 
      if (line==null) 
      { 
       break; 
      } 
      var numArray = line.Split('\t'); 
      col1.Add(Int32.Parse(numArray[0])); 
      col2.Add(Int32.Parse(numArray[1])); 
      col3.Add(Int32.Parse(numArray[2])); 
     } 
    } 

    var Foo = col1.OrderByDescending(x=>x); 
    foreach (var element in Foo) 
    { 
     Console.WriteLine (element); 
    } 
0
ArrayList col1 = new ArrayList(); 
ArrayList col2 = new ArrayList(); 
ArrayList col3 = new ArrayList(); 
using (StreamReader sr = new StreamReader(@"Sample.txt")) 
{ 
    string line; 
    while ((line = sr.ReadLine()) != null) 
    { 
     string[] split = Regex.Split(line, @"\s+"); 

     if (split.Count() == 3) 
     { 
      col1.Add(Convert.ToInt32(split[0])); 
      col2.Add(Convert.ToInt32(split[1])); 
      col3.Add(Convert.ToInt32(split[2])); 
     } 
    } 
} 

// sort all columns 
col1.Sort(); 
col2.Sort(); 
col3.Sort(); 

// output is largest to smallest so invert sort 
for (int i = col1.Count -1 ; i >= 0; i--) 
{ 
    Console.WriteLine(string.Format("{0}\t{1}\t{2}", col1[i], col2[i], col3[i])); 
} 
Смежные вопросы