Smaug
Smaug

Reputation: 2673

Linq syntax required for string array to string conversion

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

Answers (7)

ywm
ywm

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

Sergey Berezovskiy
Sergey Berezovskiy

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

Thomas Levesque
Thomas Levesque

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

Tim Schmelter
Tim Schmelter

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

Slawomir Pasko
Slawomir Pasko

Reputation: 907

You don't need linq for that. Just use simple string.Join() method.

string.Join("\n",allfiles);

Upvotes: 0

Rajesh Subramanian
Rajesh Subramanian

Reputation: 6490

Following should work

String.Join(delimiter,stringArray);

Upvotes: -1

Jamiec
Jamiec

Reputation: 136094

Easy enough

String.Join("\n",allFiles)

Upvotes: 5

Related Questions