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

C# 如何更新列表C中的整个对象?,c#,C#,我有一个对象列表,我想用新对象替换列表中的一个对象: public Parent AppendParentChildren(Request request) { var Children = request.Parent.Children.ToList(); if (Children.Any(x => x.TrackingNumber == request.Child.TrackingNumber)) { //

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

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;
        }
    }
}
项为只读,因此无法替换列表中的对象


有什么建议吗?

您不能更改foreach迭代的成员,因为foreach实现了只读的IEnumerable类型。 解决方案是将扩展方法内的项列表转换为可读写的列表。然后,您需要确定要替换列表中的哪些项并对其进行更新。下面是假设您处于可以使用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上给出了一个工作示例,尽管有点臃肿


还值得注意的是,尽管看起来您正在更改childList,但实际上它引用回了原始列表,没有创建副本。有关此的详细信息

您听说过循环吗?我不明白您想做什么,抱歉。你能编辑你的帖子并澄清一下吗?你确定要用同一个对象替换具有相同跟踪编号的多个对象吗?此时您将在列表中复制该对象。由于您将子对象公开为IEnumerable,因此表示为只读语义。如果要更改该值,请将其更改为“列表”。