null null - 4 months ago 10
C# Question

Put file name into list if it contains a certain number

I'm starting to write a downloader.. But I want to put the files that need to extract, are required, or option in a list for later reference by the downloader.

A sample string that is fed into it would be like this:

file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2


What i want to do, is get an output like this:


Extract: file0.txt file1.txt

Required: file2.txt

Optional: file3.txt file4.txt, file5.txt


But I have no clue how to go about doing this.
The downloader will use these lists to download files the external app needs.

Answer

I'm assuming that the numbers that come after each file name are supposed to indicate what kind of file they are?

Now you definitely should try to solve this problem yourself - because thats how you learn, but here is a fairly elegant LINQ solution that creates an output identical to the example you posted.

// Define this in your class
enum FileType : byte
{
    Extract = 0,
    Required = 1,
    Optional = 2,
}

static void Main(string[] args)
{
    string input = "file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2";

    // create list of files
    var list = input.Split(' ').Select(file =>
    {
        var spl = file.Split(':');
        var type = (FileType)Enum.Parse(typeof(FileType), spl[1]);
        return new { Name = spl[0], Type = type };
    }).ToArray();

    // group by type and write to console
    var group = list.GroupBy(l => l.Type);
    foreach (var g in group)
    {
        Console.WriteLine("{0}: {1}", g.Key, String.Join(",", g.Select(a => a.Name)));
    }
}