c#更新列表中的项目 [英] c# Update item in list

查看:100
本文介绍了c#更新列表中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

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;
    }
}

,然后在我的代码中实例化一个List<Item>并向其中添加10个项目.

and then in my code I instantiate a List<Item> and add 10 items to it.

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

如果现在我要遍历列表,并且对每个项目调用扩展方法并修改其name属性,如何更新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?

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

推荐答案

由于您的方法返回了修改后的item,因此您的foreach循环已经可以满足您的要求.

Since your method returns the same item that it modifies, your foreach loop already does what you want.

您可以生成一个新列表,然后为较短的代码重新分配items:

You could produce a new list and reassign items for a somewhat shorter code:

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

这篇关于c#更新列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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