简体   繁体   English

使用LINQ在列表的所有元素上应用谓词

[英]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.

相关问题 使用Linq方法时.Any( <predicate> ) 和所有( <predicate> )在IList上,谓词是否以严格的顺序应用于列表? - When using the Linq methods .Any(<predicate>) and .All(<predicate>) on an IList, are the predicates applied to the list in a strict sequence? 将方法应用于LINQ可枚举的所有元素 - Apply method to all elements in enumerable with LINQ 使用lambda,如何将现有功能应用于列表的所有元素? - using lambda, how to apply an existing function to all elements of a list? 如何检查列表中的所有元素是否对使用Linq的属性返回true? - How to check if all of the elements in a list return true for a property using Linq? 使用Linq对列表中最后一个元素以外的所有元素执行操作 - Perform manipulation on all elements except last element in a List using Linq 检查字符串包含使用Linq且不区分大小写的列表中的所有元素 - Check String contain all elements in list using Linq and case insensitive 使用(LINQ / Predicate)将DataTable的所有列名称转换为字符串数组 - Get all column names of a DataTable into string array using (LINQ/Predicate) 列表上的动态Linq查询 <T> 使用谓词生成器 - Dynamic Linq query on List <T> using Predicate Builder 使用 LINQ 从列表中获取所有相同的元素 - Take all the same elements from list with LINQ 如何将一个方法应用于所有列表成员使用非常短的linq并省略lambda? - How apply a method to all list members using very short linq with lambda omitted?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM