如何更新列表C#中的整个对象?

时间:2015-02-09 16:42:05

标签: c#

我有一个对象列表,我想用新对象替换列表中的一个对象:

public Parent AppendParentChildren(Request request)
    {
        var Children = request.Parent.Children.ToList();
        if (Children.Any(x => x.TrackingNumber == request.Child.TrackingNumber))
        {
            //Here I want to replace any Children that have the same tracking number in the list with the new Child passed in
        }
        else
        {
            Children.Add(request.Child);
        }
        request.Parent.Children = Children;
        return request.Parent;
    }

public class Request
{
    public Parent Parent { get; set; }
    public Child Child { get; set; }

}

public class Parent 
{
    public IEnumerable<Child> Children {get;set;}
}

如果我尝试在循环中使用它:

public static class Extension
{
    public static void Update<T>(this List<T> items, T newItem)
    {
        foreach (var item in items)
        {
        //this
            item = newItem;
        }
    }
}

项目是只读的,因此我无法替换列表中的对象。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您无法更改foreach迭代的成员,因为foreach实现了只读的IEnumerable类型。 解决方案是将扩展方法中的项列表转换为List(可读写)。然后,您需要确定要替换的列表中的哪些项目并更新它们。下面是Update扩展方法的样子(假设您处于可以使用LINQ的情况)

public static class Extension
{
    public static void Update<T>(this List<T> items, T newItem)
    {   
        var childList = items as List<Child>;
        var newChildItem = newItem as Child;
        var matches = childList.Where(x => x.TrackingNumber == newChildItem.TrackingNumber).ToList();
        matches.ForEach(x => childList[childList.IndexOf(x)] = newChildItem);
    }
}

我在dotnetfiddle上放了一个有效的例子(尽管有些臃肿) https://dotnetfiddle.net/MJ5svP

同样值得注意的是,尽管看起来你正在改变childList,但实际上它已被引用回原始列表而不创建副本(关于此here的更多信息)