C#-使用Lambda表达式或LINQ填充列表 [英] C# - Populate a list using lambda expressions or LINQ

查看:106
本文介绍了C#-使用Lambda表达式或LINQ填充列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有一段时间了,因为我已经使用过lambda表达式或LINQ,并且想知道如何使用这两种方法来执行以下操作(我知道我可以使用foreach循环,这只是出于好奇).

我有一个字符串路径数组(如果这里是数组或列表,它是否有所不同?),我想从中返回仅包含文件名的新列表.

即使用foreach循环将是:

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

return listToReturn;

我将如何对lambda和LINQ进行相同的处理?

就我而言,我将返回的列表用作ListBox(WPF)的ItemsSource,因此我假设它需要是一个列表,而不是IEnumerable ?

解决方案

您的主要工具将是.Select()方法.

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

如果它是数组或列表,会有所不同吗?

否,数组还实现了IEnumerable<T>


请注意,这种最小方法涉及到延迟执行,这意味着fileNamesIEnumerable<string>,并且仅当从源数组中获取元素时才开始遍历源数组.

如果您想要一个列表(为了安全起见),请使用

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

但是,当有许多文件时,您可能还想通过使用延迟执行源代码来朝相反的方向(更快地交错获取结果):

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

这取决于您下一步要使用fileNames做什么.

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?

解决方案

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.

这篇关于C#-使用Lambda表达式或LINQ填充列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆