Skip to content

Instantly share code, notes, and snippets.

@tonerdo
Created September 16, 2018 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonerdo/8798f463fd46b1de97f84ab14be27605 to your computer and use it in GitHub Desktop.
Save tonerdo/8798f463fd46b1de97f84ab14be27605 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace sum_files_solution
{
class Program
{
static async Task Main(string[] args)
{
List<Task<long>> tasks = new List<Task<long>>();
var files = Directory.EnumerateDirectories("files")
.SelectMany(directory => Directory.EnumerateFiles(directory));
foreach (var file in files)
{
var task = Task.Run(() => SumFile(file));
tasks.Add(task);
}
var result = await Task.WhenAll(tasks);
var sumOfFiles = result.Sum();
long SumFile(string file)
{
long sum = 0;
foreach (var line in File.ReadLines(file))
{
foreach (var shard in line.Split(','))
sum += int.Parse(shard);
}
return sum;
}
// Total: 49947871404
Console.WriteLine("Total: {0}", sumOfFiles);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment