1

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] ;
4
  • 1
    I suppose you mean allfiles[i] Commented Mar 7, 2013 at 13:29
  • Your above code can't solve your problem. Commented Mar 7, 2013 at 13:30
  • 1
    @HamletHakobyan Obviously. If it could, why would he be asking here? Commented Mar 7, 2013 at 13:40
  • Thanks to all. Your answers helped me. Commented Mar 7, 2013 at 13:41

7 Answers 7

7

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);
Sign up to request clarification or add additional context in comments.

Comments

5

Easy enough

String.Join("\n",allFiles)

Comments

4

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());

Comments

2

If it's required to use LINQ:

var result = allFiles.Aggregate(new StringBuilder(),
                                (sb, s) => sb.AppendLine(s),
                                sb => sb.ToString());

Comments

0

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

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

Comments

-1

Following should work

String.Join(delimiter,stringArray);

Comments

-1

You don't need Linq to do this you can use the string.Join() method instead.

String strFileName = string.Join("\n", allfiles);

1 Comment

There is no overload of String.Concat which takes a string and an IEnumerable<string>

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.