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 */

I have an array of file names , and i want to extract part of name from the array for each file name

example:

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

Now I want to use Linq to extract an array out of the above array , which gives me only

policy001,policy002,policy003,policy004

Can you please help me? I am new to lambda expression.

3
  • 2
    @DanielMann I think the first section is what he has tried but obviously that's not clear enough due to formatting. Dec 14, 2012 at 15:56
  • 2
    Is the 0-, 1- and so on, part of the filename, or just an index? Dec 14, 2012 at 16:00
  • @HansKesting this is what confused me when I put my answer Dec 14, 2012 at 16:02

4 Answers 4

4
List<string> output = fileList.Select(fileName => fileName.Split(new char[] {'-','_'})[1]).ToList()
1
  • +1 for the answer, was going to change my answer after I understood what was being asked for haha. Dec 14, 2012 at 16:00
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

If the numbers are indexes

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

If the numbers are part of the file name

string[] output = fileList.Select(fileName => fileName.Split(new char[] {'-', '_'})[1]).ToArray();
2
  • That will return the number at the start too Dec 14, 2012 at 15:57
  • @JustinHarvey I see the formatting of the question made me think that the numbers represented the indexes... Dec 14, 2012 at 15:59
0

If it's always so strict:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.