Advertisement
sashomaga

Sort string file

Jan 27th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. //Write a program that reads a text file containing a list of strings, sorts them and saves them to another text file
  6. class Sort
  7. {
  8.     static void Main()
  9.         {
  10.             using(StreamReader reader = new StreamReader("unsorted.txt"))
  11.             using (StreamWriter writer = new StreamWriter("sorted.txt"))
  12.             {
  13.                 List<string> unsorted = new List<string>();
  14.                 ReadFile(reader, unsorted);
  15.                 List<string> sorted = new List<string>();
  16.                 SortList(unsorted, sorted);
  17.                 WriteFile(writer, sorted);
  18.             }
  19.         }
  20.  
  21.     private static void WriteFile(StreamWriter writer, List<string> sorted)
  22.     {
  23.         for (int i = 0; i < sorted.Count; i++)
  24.         {
  25.             writer.WriteLine(sorted[i]);
  26.         }
  27.     }
  28.  
  29.     private static void SortList(List<string> unsorted, List<string> sorted)
  30.     {        
  31.         var sort = from s in unsorted
  32.                    orderby s
  33.                    select s;
  34.         foreach (var item in sort)
  35.         {
  36.             sorted.Add(item);
  37.         }
  38.     }
  39.  
  40.     private static void ReadFile(StreamReader reader, List<string> unsorted)
  41.     {      
  42.         string line;
  43.         while ((line = reader.ReadLine())!=null)
  44.         {
  45.             unsorted.Add(line);
  46.         }        
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement