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

csharp 复制代码
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}");
        }
    }
相关推荐
波力海苔夹心脆67513 小时前
C# WPF 资源字典详解:ResourceDictionary、MergedDictionaries 与自定义控件案例
开发语言·c#·wpf·入门教程·resource·资源字典
AI导出鸭PC端16 小时前
Perplexity批量导出没有PDF模式?AI导出鸭插件补上最后一块拼图
人工智能·pdf·c#·ai导出鸭
Risehuxyc17 小时前
C# 选用更流行的语言版本
c#
淡海水2 天前
09-04-内存-Unity原生对象生命周期
unity·c#·游戏引擎·gc
吴可可1232 天前
富怡CAD二次开发指南
c#
1-1=02 天前
C# IO和序列化
c#·.net·.netcore
寂寞的船2 天前
【Unity Bug挑战】第10期 SerializeReference 内存泄漏之谜
unity·c#·游戏引擎·bug
CSharp精选营2 天前
从控制台到「会动手」的 AI:用 Semantic Kernel 搭应用(小白教程)
c#·.net·ai agent·semantickernel·functioncalling
宝桥南山3 天前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore
1-1=03 天前
C# 中 Lambda、Linq 与 Expression
c#·linq