C#中的聪明的正则表达式和LINQ

时间:2015-02-28 00:11:52

标签: c# linq

我有一个目录。在这个目录中有很多不同的文件。我只需要缩略图。所以我写了一个正则表达式来匹配这些文件。

然后,让所有这些匹配文件 - 我想创建一个字典:

  • 密钥作为文件名中提取的数字(匹配的数字 - 见下面的代码)
  • 值为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);
        }
    

我真的相信这可以用非常简短明了的方式写出来。你能帮我吗?

已编辑的解决方案

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);
}

1 个答案:

答案 0 :(得分:2)

这是我能想到的最好的:

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);
}

我必须将IReadOnlyDictionary<int, Image>更改为IDictionary<int, Image>才能使作业完成。