有没有一种方法可以使用LINQ在适当位置修改列表?

编程入门 行业动态 更新时间:2024-10-26 02:25:16
本文介绍了有没有一种方法可以使用LINQ在适当位置修改列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我要执行以下操作:

If I want to do the following:

List<string> listOfStrings = new List<string>(); listOfStrings.Add("13"); listOfStrings.Add("14"); listOfStrings.Add("FooBar"); listOfStrings.Add("Dummy14Item"); listOfStrings.Add("Brontosaurus165LT"); //... add items here ... // iterate through the list and find all items // ending with "LT" and remove the last two characters // from those items, but leave the list intact for (int i = 0; i < listOfStrings.Count; i++) { if (listOfStrings[i].EndsWith("LT")) listOfStrings[i] = listOfStrings[i].Replace("LT", ""); } // list should now be // // 13 // 14 // FooBar // Dummy14Item // Brontosaurus165 // // can I make this change with LINQ?

因此,有一种方法可以对列表t进行投影.除了修改外,基本上包含相同的项目?我试过了

So is there a way to make a projection of the List<t> that contains essentially the same items except for the modification? I tried

listOfStrings.ForEach(x => { if (x.EndsWith("LT")) x = x.Replace("LT", ""); });

但是,除非我做错了什么,否则它似乎不起作用.原因之一可能是因为ForEach函数将Action<T>委托作为其参数,该委托通过值而不是通过引用传递T obj. 有人暗示吗?我只是讨厌for(int i;i < list.Count; i++ )的第一个功能块,似乎是schoolschool. Brian

But, unless I am doing something incorrectly, it doesn''t seem to be working. One reason may be because the ForEach function takes as its parameter an Action<T> delegate, which passes T obj by value, not by reference. Does anyone have a hint? I just hate the first block with the for(int i;i < list.Count; i++ ), it seems so gradeschool. Brian

推荐答案

int i = 0; listOfStrings.ForEach(x => { if (x.EndsWith("LT")) { listOfStrings[i] = x.Replace("LT", string.Empty); } i++; } );

更多推荐

有没有一种方法可以使用LINQ在适当位置修改列表?

本文发布于:2023-11-23 18:24:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622441.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   位置   方法   列表   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!