如何更新ObservableCollection类中的单个项?

问题描述 投票:35回答:4

如何更新ObservableCollection类中的单个项?

我知道怎么做Add。我知道如何在“for”循环中一次搜索ObservableCollection一个项目(使用Count作为项目的表示)但是如何查找现有项目。如果我执行“foreach”并找到需要更新的项目,如何将其重新放入ObservableCollection>

c# .net silverlight linq
4个回答
37
投票

您不需要删除项目,更改,然后添加。您可以简单地使用LINQ FirstOrDefault方法使用适当的谓词查找必要的项并更改它的属性,例如:

var item = list.FirstOrDefault(i => i.Name == "John");
if (item != null)
{
    item.LastName = "Smith";
}

删除或添加项目到ObservableCollection将生成CollectionChanged事件。


33
投票

您通常不能更改您正在迭代的集合(使用foreach)。当然,解决这个问题的方法是在更改它时不要迭代它。 (x.Id == myId和LINQ FirstOrDefault是您的标准/搜索的占位符,重要的部分是您已获得对象的对象和/或索引)

for (int i = 0; i < theCollection.Count; i++) {
  if (theCollection[i].Id == myId)
    theCollection[i] = newObject;
}

要么

var found = theCollection.FirstOrDefault(x=>x.Id == myId);
int i = theCollection.IndexOf(found);
theCollection[i] = newObject;

要么

var found = theCollection.FirstOrDefault(x=>x.Id == myId);
theCollection.Remove(found);
theCollection.Add(newObject);

要么

var found = theCollection.FirstOrDefault(x=>x.Id == myId);
found.SomeProperty = newValue;

如果最后一个例子会这样做,你真正需要知道的是如何让你注意你的ObservableCollection知道这个变化,你应该在对象的类上实现INotifyPropertyChanged并确保在你改变的属性改变时引发PropertyChanged (理想情况下,如果你有接口,它应该在所有公共属性上实现,但功能上当然它真的只对你要更新的那些有用)。


5
投票

以下是Tim S's examples作为Collection类顶部的扩展方法:

CS with FirstOrDefault

public static void ReplaceItem<T>(this Collection<T> col, Func<T, bool> match, T newItem)
{
    var oldItem = col.FirstOrDefault(i => match(i));
    var oldIndex = col.IndexOf(oldItem);
    col[oldIndex] = newItem;
}

CS with Indexed Loop

public static void ReplaceItem<T>(this Collection<T> col, Func<T, bool> match, T newItem)
{
    for (int i = 0; i <= col.Count - 1; i++)
    {
        if (match(col[i]))
        {
            col[i] = newItem;
            break;
        }
    }
}

Usage

想象一下,你有这个类设置

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

您可以调用以下任一函数/实现,其中match参数用于标识您要替换的项目:

var people = new Collection<Person>
{
    new Person() { Id = 1, Name = "Kyle"},
    new Person() { Id = 2, Name = "Mit"}
};

people.ReplaceItem(x => x.Id == 2, new Person() { Id = 3, Name = "New Person" });

VB with Indexed Loop

<Extension()>
Public Sub ReplaceItem(Of T)(col As Collection(Of T), match As Func(Of T, Boolean), newItem As T)
    For i = 0 To col.Count - 1
        If match(col(i)) Then
            col(i) = newItem
            Exit For
        End If
    Next
End Sub  

VB with FirstOrDefault

<Extension()>
Public Sub ReplaceItem(Of T)(col As Collection(Of T), match As Func(Of T, Boolean), newItem As T)
    Dim oldItem = col.FirstOrDefault(Function(i) match(i))
    Dim oldIndex = col.IndexOf(oldItem)
    col(oldIndex) = newItem      
End Sub

2
投票

这取决于它是什么类型的对象。

如果它是普通的C#类,只需更改对象的属性即可。您无需对集合执行任何操作。即使对象的属性发生更改,该集合仍保持对对象的引用。对象的更改不会触发集合本身的更改通知,因为集合实际上没有更改,只是其中的一个对象。

如果它是一个不可变的C#类(如字符串),struct或其他值类型,则必须删除旧值并添加新值。

© www.soinside.com 2019 - 2024. All rights reserved.