简体   繁体   中英

What to use instead of Concat in string lists in C#

I have these lists of strings

List<string> files = new List<string>
                    (System.Linq.Enumerable.Concat
                    (System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "*.*"),
                    System.IO.Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "*.pdf")));

I want to refactor code and I want to use something more efficient or faster than concat.How can I do that? Thanks

To get a List<string> of all files, you can write:

using System.IO;
using System.Linq;

string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var files = Directory.GetFiles(path, "*.*").ToList();

This will includes all PDF.

If you don't need a List<> for a special purpose, you can directly manipulate the resulting string array of GetFiles:

string[] files = Directory.GetFiles(path, "*.*");

Or simply:

var files = Directory.GetFiles(path, "*.*");

This will avoid the memory and time needed to do the conversion to a generic list of strings.

You can access items and loop foreach the same with an array or a list as they implement IEnumerable and have indexer.

A list is only useful if you need to easily manipulate items such as adding and removing, or want an OOP object for any reason.

Also as suggested by @mjwills you can use EnumerateFiles instead of GetFiles : the first time you will parse the list you don't need to wait for the full populating and there will be no eventual lag in case of lots of files:

var files = Directory.EnumerateFiles(path, "*.*");

foreach (var filePath in files) ...

But it will re-scan the system file every time you perform a parsing and this is useful only if one parsing is made or if realtime parsing is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM