迭代文件并选择最接近我的参数

时间:2011-05-06 08:23:24

标签: c# asp.net directory iteration

我想遍历一个文件夹,该文件夹可以包含以下名称的文件:

1.XML
2.XML
3.XML
4.XML

现在我想选择最接近我分配给searchmethod但不高于它的数字的文件。

e.g。在文件夹中有1,3,5和8.xml,我的参数是6,我看到6不存在,8是太高,然后挑选5!

我已经遇到了Directory.GetFiles - 方法,但由于它返回整个路径,这将是一个相当讨厌的字符串切割和比较,是否有一个更优雅的解决方案来解决我的问题?提前谢谢!

3 个答案:

答案 0 :(得分:3)

快速而又脏,没有检查以确保文件名实际上可以解析为数字(即,如果存在非数字命名的XML文件,则会失败)。留给读者练习强化这种方法。

Directory.GetFiles(@"C:\somePath" , "*.xml")
.Select(f => new{fn = Path.GetFileNameWithoutExtension(f) , path = f})
.Select(x => new{fileNum = int.Parse(x.fn) , x.path})
.OrderBy(x => x.fileNum)
.TakeWhile(x => x.fileNum <= MYPARAM)
.Select(x => x.path)
.LastOrDefault()

答案 1 :(得分:2)

您可以将Directory.GetFilesPath.GetFileNameWithoutExtension(path)结合使用。

所以,比如:

foreach (file in Directory.GetFiles("c:\\temp")) 
{
    int myInt = Int32.Parse(Path.GetFileNameWithoutExtension(file));
}

解决整个问题的一个LINQ-y解决方案可能是:

int maxFileId = 2;
int myFileNumber = Directory.GetFiles(@"C:\TEMP1\test\EnvVarTest\Testfiles")
    .Select(file => Int32.Parse(Path.GetFileNameWithoutExtension(file)))
    .Where(i => i <= maxFileId)
    .Max();

答案 2 :(得分:2)

我显然比其他人都慢一些但我认为自从我写完之后就会发布它。

class Program
{
    public class NumberedXmlFile
    {
        public NumberedXmlFile(string fullPath)
        {
            FullPath = fullPath;
        }
        public string FullPath { get; set; }
        public int FileNumber
        {
            get
            {
                string file = Path.GetFileNameWithoutExtension(FullPath);

                return Convert.ToInt32(file);
            }
        }
    }

    static void Main(string[] args)
    {
        const int targetFileNameNumber = 4;
        const string directoryPathContainingFiles = @"C:\temp";

        IEnumerable<NumberedXmlFile> numberedXmlFiles = Directory.GetFiles(directoryPathContainingFiles).Select(f => new NumberedXmlFile(f));

        NumberedXmlFile theFileIamLookingFor = numberedXmlFiles.OrderBy(f => Math.Abs(f.FileNumber - targetFileNameNumber)).FirstOrDefault();
    }
}