none
Write To Text File In Ascending Order RRS feed

  • Question

  • Good morning, I am using this syntax to write extensions and count to a text file using StreamWriter.  How could this be altered so that the content is written to the text file in ascneding order?

    public static void GetExtensionList(string filepath)
    {
      string filename = filepath + "\\ Extension.txt";
      var di = new DirectoryInfo(filepath);
      var extensionCounts = di.EnumerateFiles("*.*", SearchOption.AllDirectories)
      .GroupBy(x => x.Extension)
      .Select(g => new { Extension = g,Key, Count = g.Count() })
      .ToList();
      
      foreach (var group in extensionCounts)
        using (var sw = new StreamWriter(filename, true)
          sw.WriteLine(group.Count + " = " + group.Extension);
    }

    Tuesday, September 4, 2018 3:10 PM

Answers

  • It depends if you want to order by extension name or the count of files with extension, but it's quite trivial using OrderBy like:

    var extensionCounts = di.EnumerateFiles("*.*", SearchOption.AllDirectories)
      .GroupBy(x => x.Extension)
      .Select(g => new { Extension = g,Key, Count = g.Count() })
      .OrderBy(x=>x.Count) // note this order by line
      .ToList();

    You can either do by Extension and Count as per your need:

    .OrderBy(x=>x.Count) // ascending by Count .OrderBy(x=>x.Extension) // ascending by Extension name

    You complete method would look like following:

    public static void GetExtensionList(string filepath)
    {
      string filename = filepath + "\\ Extension.txt";
      var di = new DirectoryInfo(filepath);
      var extensionCounts = di.EnumerateFiles("*.*", SearchOption.AllDirectories)
      .GroupBy(x => x.Extension)
      .Select(g => new { Extension = g,Key, Count = g.Count() })
      .OrderBy(x=>x.Count) // note this order by line
      .ToList();
      
      foreach (var group in extensionCounts)
        using (var sw = new StreamWriter(filename, true)
          sw.WriteLine(group.Count + " = " + group.Extension);
    }

    You can also do with the extension name, you will just need to do OrderBy(x=>x.Extension) for that.

    Hope it helps!


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites




    • Edited by Ehsan Sajjad Tuesday, September 4, 2018 3:41 PM
    • Proposed as answer by Ehsan Sajjad Tuesday, September 4, 2018 4:25 PM
    • Marked as answer by IndigoMontoya Tuesday, September 4, 2018 7:20 PM
    Tuesday, September 4, 2018 3:38 PM