Reputation: 2673
I've the list of selected files in a array from particular folder.
String[] allfiles = System.IO.Directory.GetFiles(Target, "*.*", System.IO.SearchOption.AllDirectories);
I required to convert all of this files into the string variable and each line append with "\n" character with help of LINQ. I can do it as like below with help of looping but i required in LINQ Syntax.
String strFileName = string.Empty;
for ( int i = 0; i < allfiles.Length ; i++)
strFileName = strFileName + "\n" + allfiles[1] ;
Upvotes: 1
Views: 228
Reputation: 1127
You don't need Linq to do this you can use the string.Join() method instead.
String strFileName = string.Join("\n", allfiles);
Upvotes: -1
Reputation: 236208
If it's required to use LINQ:
var result = allFiles.Aggregate(new StringBuilder(),
(sb, s) => sb.AppendLine(s),
sb => sb.ToString());
Upvotes: 2
Reputation: 292405
You don't need Linq to do that, you can use the String.Join
method as illustrated in Jamiec's answer.
Now, if you really want to do it with Linq, you could use Aggregate
:
string strFileName = allfiles.Aggregate("", (acc, file) => acc + "\n" + file);
Or better, using a StringBuilder
:
string strFileName = allfiles.Aggregate(
new StringBuilder(),
(acc, file) => acc.AppendLine(file),
acc => acc.ToString());
Upvotes: 4
Reputation: 460078
First, i would use Directory.EnumerateFiles
instead, so you don't need to wait until all files are read. Then you can use string.Join(Environment.NewLine, allFileNames)
:
IEnumerable<string> allFileNames = Directory.EnumerateFiles(Target, "*.*", System.IO.SearchOption.AllDirectories);
string strFileNames = string.Join(Environment.NewLine, allFileNames);
Upvotes: 7
Reputation: 907
You don't need linq for that. Just use simple string.Join() method.
string.Join("\n",allfiles);
Upvotes: 0
Reputation: 6490
Following should work
String.Join(delimiter,stringArray);
Upvotes: -1