ObservableCollection新增数据前判断数据是否存在

avatar
作者
猴君
阅读量:0
 public class MyDataModel {     public int Id { get; set; }     public string Name { get; set; }       }  public static void Main()     {         // 创建 ObservableCollection         ObservableCollection<MyDataModel> myDataCollection = new ObservableCollection<MyDataModel>         {             new MyDataModel { Id = 1, Name = "Item 1" },             new MyDataModel { Id = 2, Name = "Item 2" },             new MyDataModel { Id = 3, Name = "Item 3" }         };          // 要添加的项         MyDataModel newItem = new MyDataModel { 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}");         }     } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!