In the code below, I need to group the files produced by the XML file. Sort the table by the byte size value of the Size column in descending order. Implement this function using LINQ queries making use of group by and orderby. I need help on modifying this code to work.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Collections; using System.Xml.Linq; using System.Xml; namespace SampleConsoleApp1 { class FileInfoFromDirectory { static void Main(string[] args) { String localPath = @" "; String fileName = @" "; List fileInfo = new List(); List fileTypes = new List(); List FileList = new List(); Console.WriteLine("Directory to search for files: " + localPath); Console.WriteLine("Ouput File Name: " + fileName); foreach (string filename in Directory.EnumerateFiles(@localPath, "*.*", SearchOption.AllDirectories)) { // added the name of file foreach (FileInfo info in EnumerateFilesRecursively1(filename)) { FileList.Add(info); if (!fileTypes.Contains(info.Extension.ToLower())) { fileTypes.Add(info.Extension.ToLower()); } } } foreach (var type in fileTypes) { var fileCount = 0; long totalSize = 0; foreach (FileInfo info in FileList) { if (type.Equals(info.Extension.ToLower())) { fileCount++; totalSize += info.Length; } } fileInfo.Add(new FileDetails { FileType = type, NumberOfFiles = fileCount, TotalSize = FormatByteSize(totalSize) }); } WriteAsXML(fileInfo, localPath, fileName); Console.WriteLine("Press any key to exit."); Console.ReadKey(); } static void WriteAsXML(List details, string localPath, string outputFile) { TextWriter tw = new StreamWriter(@localPath + outputFile); foreach (var v in details) { XElement doc = new XElement("Data", new XElement("FileType", v.FileType), new XElement("FileCount", v.NumberOfFiles), new XElement("TotalSize", v.TotalSize) ); tw.WriteLine(doc); } tw.Close(); } static IEnumerable EnumerateFilesRecursively1(string path) { FileInfo info = new FileInfo(@path); yield return info; } static string FormatByteSize(long byteSize) { string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; if (byteSize == 0) return "0" + suf[0]; long bytes = Math.Abs(byteSize); int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024))); double num = Math.Round(bytes / Math.Pow(1024, place), 1); return (Math.Sign(byteSize) * num).ToString() + suf[place]; } } public class FileDetails { public string FileType { get; set; } public int NumberOfFiles { get; set; } public string TotalSize { get; set; } } }