Daniel Lip
Daniel Lip

Reputation: 11319

How can i format each string in the List?

I have this function and I need it to format the strings in the list to be with http:// in the beginning:

        private List<string> offline(string targetDirectory)
        {

            List<string> directories = new List<string>();

            try
            {
                string[] dirs = Directory.GetDirectories(targetDirectory, "*.*", SearchOption.TopDirectoryOnly);
                for (int i = 0; i < dirs.Length; i++)
                {

                    directories.Add(dirs[i]);
                }
            }
            catch
            {

            }        
            return directories;    
        }

The function return a List of strings of directories in the hard disk. Like c:\ and c:\windows

I want that the List in the end will be instead of c:\\ and c:\\windows in index[0] and index[1] to be formatted to: http://c:\ and http://c:\windows and http://c:\temp so each string the List will be with http:// in the beginning.

How can I do it?

Upvotes: 0

Views: 100

Answers (2)

hungryMind
hungryMind

Reputation: 6999

Why not append while adding to list

directories.Add("http://" + dirs[i]);

Or

return directories.Select(rs=> "http://" + rs).ToList()

Or

directories.ForEach(rs=>rs= "http://" + rs);
return directories;

Upvotes: 0

Habib
Habib

Reputation: 223237

so each string the List will be with http:// in the beginning.

List<string> newList =  directories.Select(r=> "http://" + r).ToList();

Or

var list2 = directories.Select(r => string.Concat("http://", r)).ToList();

Upvotes: 3

Related Questions