[英]Apply a predicate on all elements of a list using LINQ
I want to update a list by applying a predicate function on every elements. 我想通过对每个元素应用谓词函数来更新列表。
Here's how I would do it without using LINQ: 以下是我不使用LINQ的方法:
for(int i = 0; i < filesToCheck.Count; i++)
{
while (filesToCheck[i][0] == '/' || filesToCheck[i][0] == '\\')
filesToCheck[i] = filesToCheck[i].Substring(1);
}
How can I do that with LINQ? 我怎么能用LINQ做到这一点?
If all you need is to remove some characters from start of every fileName, you can use TrimStart
for that, and then: 如果你需要的是从每个fileName的开头删除一些字符,你可以使用TrimStart
,然后:
var list = filesToCheck.Select(f => f.TrimStart('/', '\\'));
EDIT: you could do this without LINQ, of course, but the main issue here is your while
loop, rather than the use of for
: it took me a few seconds to mentally parse the while loop to figure out what it does. 编辑:当然,你可以在没有LINQ的情况下做到这一点,但这里的主要问题是你的while
循环,而不是for
的用法:我花了几秒钟精神解析while循环来弄清楚它的作用。 This does not convey intent, I have to mentally execute it to understand it. 这并没有传达意图,我必须在心理上执行它才能理解它。 Alternatively, you could rewrite it like this: 或者,您可以像这样重写它:
for (int i = 0; i < filesToCheck.Count; i++)
{
filesToCheck[i] = GetValueWithoutSlashes(filesToCheck[i]);
}
then it would be clear to everyone reading this, and also allowing you to change implementation of GetValueWithoutSlashes
to be whatever you want, eg 然后每个人都会清楚地阅读这个内容,并且允许您将GetValueWithoutSlashes
实现更改为您想要的任何内容,例如
private string GetValueWithoutSlashes(string value)
{
return value.TrimStart('/', '\\');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.