[英]C# how can I sort a list of file by index using linq
Hello I need to sort all the files I have in a folder but I got stuck because I need to sort them by index. 您好我需要对文件夹中的所有文件进行排序,但我遇到了问题,因为我需要按索引对它们进行排序。 I'll give you an example: 我给你举个例子:
My files are formatted like this: dateHoursMinutes_index_nameOfFile.dat 我的文件格式如下:dateHoursMinutes_index_nameOfFile.dat
Previous I used Array.Sort(_myFiles);
以前我用过Array.Sort(_myFiles);
to sort them all but now I need to sort them by index, in order. 要对它们进行排序,但现在我需要按顺序对它们进行排序。
How can I use linq to do that? 我如何使用linq来做到这一点?
Thank you 谢谢
Please refer to the following sample code: 请参考以下示例代码:
string[] _myFiles = new string[4]
{
"dateHoursMinutes_4_nameOfFile",
"dateHoursMinutes_1_nameOfFile",
"dateHoursMinutes_3_nameOfFile",
"dateHoursMinutes_2_nameOfFile"
};
char[] sep = new char[1] { '_' };
string[] sorted = _myFiles
.OrderBy(x => Convert.ToInt32(x.Split(sep)[1]))
.ToArray();
Try using Substring
of _index_
from main string to do so 尝试使用主字符串中的_index_
Substring
字符串来执行此操作
Lst<string> fileNames = new List<string>();
var SortedFiles = FileNames.OrderBy(x => Decimal.Parse(path.Substring(path.IndexOf("_") + 1, path.Substring(path.IndexOf("_") + 1).IndexOf("_"))).ToList();
Edit : to sort file name such as \\\\Programs\\\\Drop_99\\\\recepes\\\\CLF\\\\20180626113520_2_WAVES.dat
use Path.GetFileName()
编辑 :排序文件名,如\\\\Programs\\\\Drop_99\\\\recepes\\\\CLF\\\\20180626113520_2_WAVES.dat
使用Path.GetFileName()
Solution using below answer as ref. 解决方案使用以下答案作为参考
var sampl12836 = xspli.OrderBy(ele =>
{
var path = Path.GetFileName(ele);
return Decimal.Parse(path.Split('_')[1]);
}).ToList();
Solution using my answer:- 使用我的答案解决方案: -
var sorted = FileNames.OrderBy(ele =>
{
var path = Path.GetFileName(ele);
int firstIndex = path.IndexOf("_");
return Decimal.Parse(path.Substring(path.IndexOf("_") + 1, path.Substring(firstIndex + 1).IndexOf("_")));
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.