2012-12-14 80 views
3
var result=list.select(element=>element.split['_']).list(); 
/* I want to extract the part of the file name from a list of file names */ 

我有文件名称的数组,并且我想从阵列的每个文件名LINQ和字符串数组

例如提取名称的一部分:

0-policy001_Printedlabel.pdf
1- policy002_Printedlabel.pdf
2- policy003_Printedlabel.pdf
3- policy004_Printedlabel.pdf

现在我想使用LINQ提取数组超出上述阵列,这给我的只有

为policy001,policy002,policy003,policy004

你能帮帮我吗?我是lambda表达式的新手。

+2

@DanielMann我认为第一部分是他已经尝试过的,但显然由于格式不够清楚。 – LukeHennerley

+2

是“0”,“1”等等,是文件名的一部分还是只是一个索引? –

+0

@HansKesting这是什么让我困惑,当我把我的答案 – LukeHennerley

回答

1

如果数字指标

string[] output = fileList.Select(fileName => fileName.Split(new char[] {'_'})[0]).ToArray(); 

如果数字是文件名

string[] output = fileList.Select(fileName => fileName.Split(new char[] {'-', '_'})[1]).ToArray(); 
+0

这也将在开始时返回数字 –

+0

为什么downvotes?我误解了一些东西吗? – LukeHennerley

+0

@JustinHarvey我看到这个问题的格式让我觉得数字代表了索引... – LukeHennerley

4
Regex regex = new Regex(@".+(policy[0-9]+).+"); 

var newarray = yourarray.Select(d=>regex.Match(d)) 
         .Where (mc => mc.Success) 
         .Select(mc => mc.Groups[1].Value) 
         .ToArray(); 
4
List<string> output = fileList.Select(fileName => fileName.Split(new char[] {'-','_'})[1]).ToList() 
+0

+1为答案,在我理解了被问到的哈哈后会改变我的答案。 – LukeHennerley

0

的一部分,如果它总是那么严格:

string[] result = list 
    .Select(fn => Path.GetFileNameWithoutExtension(fn) 
         .Split(new[] { '-', '_' }, StringSplitOptions.None) 
         .ElementAtOrDefault(1)) 
    .ToArray();