pluralsight-linq-fundamentals/Introduction/Program.cs

53 lines
1.4 KiB
C#
Raw Permalink Normal View History

2021-02-23 16:32:29 +11:00
using System;
using System.Collections.Generic;
using System.IO;
2021-02-23 16:37:53 +11:00
using System.Linq;
2021-02-23 16:32:29 +11:00
namespace Introduction
{
class Program
{
static void Main(string[] args)
{
string path = Directory.GetCurrentDirectory();
ShowLargeFilesWithoutLinq(path);
2021-02-23 16:37:53 +11:00
Console.WriteLine("***");
ShowLargeFilesWithLinq(path);
}
private static void ShowLargeFilesWithLinq(string path)
{
var query = new DirectoryInfo(path).GetFiles()
.OrderBy(f => f.Length)
.Take(5);
foreach (var file in query.Take(5))
{
Console.WriteLine($"{file.Name,-50} : {file.Length,10:N0}");
}
2021-02-23 16:32:29 +11:00
}
private static void ShowLargeFilesWithoutLinq(string path)
{
DirectoryInfo directory = new DirectoryInfo(path);
FileInfo[] files = directory.GetFiles();
Array.Sort(files, new FileInfoComparer());
for (int i = 0; i < 5; i++)
{
FileInfo file = files[i];
Console.WriteLine($"{file.Name, -20} : {file.Length, 10:N0}");
}
}
}
public class FileInfoComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
return y.Length.CompareTo(x.Length);
}
}
}