有没有一种方法可以使用LINQ在适当位置修改列表? [英] Is there a way to use LINQ to modify a List in place?

查看:375
本文介绍了有没有一种方法可以使用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在适当位置修改列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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