简体   繁体   English

c#更新列表中的项目

[英]c# Update item in list

I have the following: 我有以下内容:

public class Item
{
   public Item()
   {

   }

   public string Name {get; set;}
}


public static class Extension
{
    public static Item Modify(this Item itm)
    {
        itm.Name = "Changed";

        return itm;
    }
}

and then in my code I instantiate a List<Item> and add 10 items to it. 然后在我的代码中实例化一个List<Item>并向其中添加10个项目。

List<Item> items = new List<Item>();  // contains 10 items
.....

If now I want to iterate my list and for each item I call the extension method and modify it's name property, how do I update the item in items list? 如果现在我要遍历列表,并且对每个项目调用扩展方法并修改其name属性,如何更新items列表中的items

foreach (Item itm in items)
{
    Item changedItem = itm.Modify();
    // update item in items list
}

Since your method returns the same item that it modifies, your foreach loop already does what you want. 因为你的方法返回相同的item ,它改变,你foreach循环已经做了你想要的东西。

You could produce a new list and reassign items for a somewhat shorter code: 您可以生成一个新列表并为较短的代码重新分配items

items = items.Select(Modify).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM