ebvtrnog
ebvtrnog

Reputation: 4377

Clever regex and LINQ in C#

I have a directory. In this directory there are lots of various files. I need only thumbnails. So I wrote a regex to match those files.

Then, having all those matches files - I would like to make a dictionary that would have:

I truly believe this could be written in a very short and clear way. Could you please help me?

Edited solution

public readonly Dictionary<int, Image> thumbnails;

public ItemData(string directory)
{
    Regex r = new Regex("^thumbnail-([0-9]+)$", RegexOptions.RightToLeft);

    thumbnails =
        Directory.GetFiles(directory)
        .Select(f => new
        {
            file = f,
            match = r.Match(Path.GetFileNameWithoutExtension(f))
        })
        .Where(x => x.match.Success)
        .Select(x => new
        {
            size = Int32.Parse(x.match.Groups[1].Value),
            image = Image.FromFile(Path.Combine(directory, x.file))
        })
        .ToDictionary(x => x.size, x => x.image);
}

Upvotes: 0

Views: 106

Answers (1)

Enigmativity
Enigmativity

Reputation: 117064

Here's the best I could come up with:

public void ItemData(string directory)
{
    var r = new Regex(directory + "\\thumbnail-([0-9]+).jpg", RegexOptions.RightToLeft);

    thumbnails =
        Directory
            .GetFiles(this.directory)
            .Select(f => new
            {
                file = f,
                result = r.Match(f).Groups[1].Value
            })
            .Where(x => x.result != "")
            .Select(x => new
            { 
                size = Int32.Parse(x.result),
                image = Image.FromFile(x.file)
            })
            .ToDictionary(x => x.size, x => x.image);
}

I had to change the IReadOnlyDictionary<int, Image> to IDictionary<int, Image> to make the assignment work.

Upvotes: 2

Related Questions