publicclassMyDataModel{publicint Id {get;set;}publicstring Name {get;set;}}publicstaticvoidMain(){// 创建 ObservableCollectionObservableCollection<MyDataModel> myDataCollection =newObservableCollection<MyDataModel>{newMyDataModel{ Id =1, Name ="Item 1"},newMyDataModel{ Id =2, Name ="Item 2"},newMyDataModel{ Id =3, Name ="Item 3"}};// 要添加的项MyDataModel newItem =newMyDataModel{ Id =2, Name ="Item 2"};// Id 已存在// 使用 LINQ 检查是否已存在if(!myDataCollection.Any(item => item.Id == newItem.Id)){
myDataCollection.Add(newItem);
Console.WriteLine($"Item with Id {newItem.Id} added.");}else{
Console.WriteLine($"Item with Id {newItem.Id} already exists.");}// 输出当前集合中的项foreach(var item in myDataCollection){
Console.WriteLine($"Id: {item.Id}, Name: {item.Name}");}}