Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Populate a list using lambda expressions or LINQ

Tags:

c#

lambda

linq

It's been a while since I've used lambda expressions or LINQ and am wondering how I would do the following (I know I can use a foreach loop, this is just out of curiosity) using both methods.

I have an array of string paths (does it make a difference if it's an array or list here?) from which I want to return a new list of just the filenames.

i.e. using a foreach loop it would be:

string[] paths = getPaths();
List<string> listToReturn = new List<string>();
foreach (string path in paths)
{
    listToReturn.add(Path.GetFileName(path));
}

return listToReturn;

How would I do the same thing with both lambda and LINQ?

EDIT: In my case, I'm using the returned list as an ItemsSource for a ListBox (WPF) so I'm assuming it's going to need to be a list as opposed to an IEnumerable?

like image 657
NRaf Avatar asked Nov 27 '22 04:11

NRaf


1 Answers

Your main tool would be the .Select() method.

string[] paths = getPaths();
var fileNames = paths.Select(p => Path.GetFileName(p));

does it make a difference if it's an array or list here?

No, an array also implements IEnumerable<T>


Note that this minimal approach involves deferred execution, meaning that fileNames is an IEnumerable<string> and only starts iterating over the source array when you get elements from it.

If you want a List (to be safe), use

string[] paths = getPaths();
var fileNames = paths.Select(p => Path.GetFileName(p)).ToList();

But when there are many files you might want to go the opposite direction (get the results interleaved, faster) by also using a deferred execution source:

var filePaths = Directory.EnumerateFiles(...);  // requires Fx4
var fileNames = filePaths.Select(p => Path.GetFileName(p));

It depends on what you want to do next with fileNames.

like image 148
Henk Holterman Avatar answered Dec 17 '22 17:12

Henk Holterman