从C#目录中的文件中获取数据,但我想对其进行排列/排序
我编写了一个代码,从目录中的所有文件中获取元数据(创建日期、上次修改日期等),并打印出文件的上次修改日期和名称 我希望它能够按照文件最后修改日期的顺序(降序)排列/排序输出。。。 我该怎么做 下面是我的代码片段:(它是一个控制台应用程序)从C#目录中的文件中获取数据,但我想对其进行排列/排序,c#,C#,我编写了一个代码,从目录中的所有文件中获取元数据(创建日期、上次修改日期等),并打印出文件的上次修改日期和名称 我希望它能够按照文件最后修改日期的顺序(降序)排列/排序输出。。。 我该怎么做 下面是我的代码片段:(它是一个控制台应用程序) 另外,fileProperties是我创建的类的实例列表(如您所见,后来转换为数组)。。。它有两个属性,它们是lastModifiedDataOffile,和fileName属性,都是字符串。重要注意事项:File.GetLastWriteTime(文件路径)
另外,fileProperties是我创建的类的实例列表(如您所见,后来转换为数组)。。。它有两个属性,它们是lastModifiedDataOffile,和fileName属性,都是字符串。重要注意事项:
File.GetLastWriteTime(文件路径)
返回DateTime
,不将其转换为字符串,而是使用DateTime
的.Date
属性只在lastModifiedDate
属性中存储日期
一旦将lastModifiedDate
存储为DateTime
类型,而不仅仅是fileProperties.ToArray()
,首先使用System.Linq
中的函数将列表的文件属性
排序为降序
按降序排列序列的元素
请在编写代码时使用适当的。由于您是初学者,从长远来看,它将对您有所帮助fileProperties.OrderByDescending(x=>x.lastModifiedDate)。ToArray()?@shree.pat18,它将不起作用,因为在OP的问题中,
lastModifiedDate
是字符串类型。如果您检查我的答案,我建议只存储日期,而不是转换字符串并从中删除的11
字符。@NabeelAnsari,您为什么要执行。在将lastModifiedDate
转换为字符串时删除(11)
?你想只存储时间吗?@prasadelkikikar是的,.Remove(11)只存储时间Date@NabeelAnsari,因此请使用.Date
属性,而不是将DateTime
转换为字符串,然后删除(错误代码)。您需要上次修改的日期和时间,这是从GetLastWriteTime()
函数获取的。只需存储它并在其上应用OrderByDescending
。我在回答中也这样做了。希望这会有帮助。关于更多细节,我为每一行添加了注释。我照你说的做了,我读了更多的文档和资料,应该可以。。。但是,输出显示“fmr1.Program+FileProperties”。。。我确实在列表中添加了一个断点,出于某种原因,它添加了“fmr1.Program+FileProperties”。。。帮助?@NabeelAnsarifmr1.Program+FileProperties
没有给出关于错误的明确信息。您是否已检查结果
变量。它是否包含基于lastModifiedDataOffile
属性的排序记录?如果与问题相关,请添加正确的错误和调用堆栈。若并没有,那个么添加一个具有适当细节的新问题。这次我在“var result=rest of the code”处插入了一个断点,看起来是这样的:它工作正常<代码>结果
的类型为列表
。我相信您正在控制台上获得fmr1.Program+FileProperties
。要在控制台上打印FileProperties
类的特定值,请重写ToString()
函数。请参考我的答案
foreach (string filepath in Directory.GetFiles(mainPath))
{
lastModified = File.GetLastWriteTime(filepath);
lastModifiedDate = lastModified.ToString().Remove(11);
fileName = Path.GetFileName(filepath);
fileName = fileName.Substring(0, fileName.Length - 4);
fileProperties.Add(new FileProperties { lastModifiedDateofFile = lastModifiedDate, fileName = fileName });
}
fileProperties.ToArray();
//(and then I print it, which comes at a later point in the code which is why I am not showing it here, it was just a Console.WriteLine command)
using System.Linq;
...
foreach (string filepath in Directory.GetFiles(mainPath))
{
//Use .Date property of DateTime.
//****Actually, you even don't need .Date property, Sorting on DateTime gives precise result as it consider seconds as well.
lastModified = File.GetLastWriteTime(filepath).Date;
//Use Path function to get name without extension.
fileName = Path.GetFileNameWithoutExtension(filepath);
//Instead of storing string as datetime, store as `Datetime`.
//I would suggest change type of `lastModifiedDateofFile` from string to DateTime
fileProperties.Add(new FileProperties { lastModifiedDateofFile = lastModified fileName = fileName });
}
var result = fileProperties
.OrderByDescending(x => x.lastModifiedDateofFile) //Order list of fileProperty by desc
.ToArray(); //Convert to array