IEnumerable中的更新项目 [英] Update item in IEnumerable
问题描述
我需要更新IEnumerable列表中的值.
I need to update a value in a IEnumerable list.
这是一个简短的IEnumerable示例:
Here is a brief IEnumerable example:
IEnumerable<string> allsubdirs = new List<string>() { "a", "b", "c" };
现在,如果我想为每个项目添加时间戳,则此方法将无效:
Now if I want to add a timestamp to each item, this doesnt work:
allsubdirs.Select(a => a = a + "_" + DateTime.Now.ToString("hhmmss")).ToList();
这也不是:
foreach (var item in allsubdirs)
item = item + "_" + DateTime.Now.ToString("hhmmss");
我使它像这样工作:
IEnumerable<string> newallsubdirs = allsubdirs.Select(a => a + "_" + DateTime.Now.ToString("hhmmss")).ToList();
allsubdirs = newallsubdirs;
但是这似乎有点像作弊.请问这样做的正确方法是什么?
but this somehow seems like cheating. Whats the proper way of doing this please?
推荐答案
Linq用于查询,而不是更新. Linq查询根据投影,过滤器等返回 new 集合.因此,您可以选择:
Linq is for querying, not updating. Linq queries return a new collection based on projections, filters etc. So your choices are:
-
将新"集合保存回变量(或在必要时添加新变量):
Save the "new" collection back to the variable (or a new variable, if necessary):
allsubdirs = allsubdirs.Select(a => a = a + "_" + DateTime.Now.ToString("hhmmss")).ToList();
使用可写接口,例如IList<T>
和for
循环:
Use a writable interface like IList<T>
and a for
loop:
IList<string> allsubdirs = new List<string>() { "a", "b", "c" };
for(int i=0; i<allsubdirs.Count(); i++)
allsubdirs[i] = allsubdirs[i] + "_" + DateTime.Now.ToString("hhmmss");
主要区别在于,Select
不会修改原始集合,而for
循环会进行修改.
The main difference is that Select
does not modify the original collection, while the for
loop does.
我的观点是Select
更加整洁,而不是作弊"-您只是在原始集合的顶部添加投影.
My opinion is that the Select
is cleaner and is not "cheating" - you're just adding a projection on top of the original collection.
这篇关于IEnumerable中的更新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!