Click here to Skip to main content
15,922,015 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am adding to array using the foreach loop. I want to do the same via linq.

My code is as below:
C#
foreach (string SourceExcelFilePath in SourceExcelTemplateCollection)
                   {
                       //Fetch the Template Id from Destination Excel Template(In DATA Folder)if any to validate if Template Id already exists
                       string SourceExcelTemplateName = Path.GetFileNameWithoutExtension(SourceExcelFilePath);
                       string[] SourceExcelTemplateId = SourceExcelTemplateName.Split('_');
                       StdExcelTemplateIdList.Add(SourceExcelTemplateId[1].ToString());
                       StdExcelTemplateIdValues = StdExcelTemplateIdList.ToArray();

                   }
Posted
Comments
Maciej Los 8-Jan-16 2:06am    
What kind of data returns SourceExcelTemplateCollection?
What returns Path.GetFileNameWithoutExtension(SourceExcelFilePath)?
If you want our help, you must be more specific.

1 solution

My best shot:
C#
var result = SourceExcelTemplateCollection
                .Select(x=>new 
                    {
                        SourceExcelTemplateId = Path.GetFileNameWithoutExtension(x).Split('_')[1]                    
                    });


It should return IEnumerable<string>. To get an array or a list of string, use ToArray() or ToList() method at the end of above statement.

[EDIT]
I suspect that you want to achieve something like this:
C#
string[] SourceExcelTemplateCollection = new string[]{@"C:\Template_C012.xslt",
		@"C:\Template_D511.xslt",
		@"C:\Template_H914.xslt",
		@"C:\Template_A011.xslt"};
		
List<string> StdExcelTemplateIdList = SourceExcelTemplateCollection
                .Select(x=>Path.GetFileNameWithoutExtension(x).Split('_')[1])
				.ToList<string>();


Result:
C012 
D511 
H914 
A011 
 
Share this answer
 
v2
Comments
[no name] 8-Jan-16 5:52am    
[EDIT]
I suspect I have voted a 5 :)
Maciej Los 8-Jan-16 5:56am    
I suspect you're not telling the truth, Bruno ;)
Thank you!
Cheers,
Maciej
[no name] 8-Jan-16 7:38am    
I'm sorry, you're right. I have voted the 5 after writing the comment :-)
Bruno
Maciej Los 8-Jan-16 7:51am    
:laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900