Reputation: 4377
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:
the value as Image
public readonly IReadOnlyDictionary<int, Image> thumbnails;
ItemData(string directory)
{
this.directory = directory;
var files = Directory.GetFiles(directory);
Regex r = new Regex(directory + "\\thumbnail-([0-9]+).jpg", RegexOptions.RightToLeft);
List<int> sizes = new List<int>();
List<Image> images = new List<Image>();
for (int i = 0; i < files.Count(); i++)
{
string result = r.Match(files[i]).Groups[1].Value;
if (result != "")
{
sizes.Add(Int32.Parse(result));
images.Add(Image.FromFile(files[i]));
}
}
thumbnails = sizes.Zip(images, (s, i) => new {s, i}).ToDictionary(item => item.s, item => item.i);
}
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
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