linq和字符串数组

时间:2012-12-14 15:54:05

标签: c# linq

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

我有一个文件名数组,我想从数组中为每个文件名提取部分名称

示例:

  

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

现在我想使用Linq从上面的数组中提取一个数组,这只给我

  

policy001,policy002,policy003,policy004

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

4 个答案:

答案 0 :(得分: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();

答案 1 :(得分:4)

List<string> output = fileList.Select(fileName => fileName.Split(new char[] {'-','_'})[1]).ToList()

答案 2 :(得分:1)

如果数字是索引

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

如果数字是文件名的一部分

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

答案 3 :(得分:0)

如果它总是如此严格:

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