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. Commented Dec 14, 2012 at 15:56
  • 2
    Is the 0-, 1- and so on, part of the filename, or just an index? Commented Dec 14, 2012 at 16:00
  • @HansKesting this is what confused me when I put my answer Commented Dec 14, 2012 at 16:02

4 Answers 4

4
List<string> output = fileList.Select(fileName => fileName.Split(new char[] {'-','_'})[1]).ToList()
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the answer, was going to change my answer after I understood what was being asked for haha.
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();

Comments

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 Comments

That will return the number at the start too
@JustinHarvey I see the formatting of the question made me think that the numbers represented the indexes...
0

If it's always so strict:

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.