gpt4 book ai didi

c# - 如何使用 LINQ 查找重复对象

转载 作者:行者123 更新时间:2023-11-30 20:41:32 27 4
gpt4 key购买 nike

我有一个具有以下内容的 Employee 类:

public class Employee
{
//EmployeeNumber cannot be the same as the Id
public int EmployeeNumber {get; set; }
public string EmployeeName {get; set }
}

最终我将用新员工更新数据库。我有一个新员工列表,还有一个存在于数据库中的现有员工列表。员工姓名可以相同,但 EmployeeNumber 必须是唯一的。我希望最终有一个重复的员工列表,该列表是通过比较我将添加到数据库中的列表与代表数据库内部内容的员工列表创建的。

使用 LINQ 获取重复员工列表的最佳方法是什么?

最佳答案

正确的做法是将 EmployeeNumber 声明为表键,这样就不需要检查重复项了。

public class Employee
{
[Key]
public int EmployeeNumber {get; set; }
public string EmployeeName {get; set }
}

同样在您的数据库中,您可以将 EmployeeNumber 声明为主键。假设您使用的是 SQL Server,您可以添加 Identity(1,1) 使其自动递增。

下面是您的表定义的示例:

CREATE TABLE Persons
(
EmployeeNumber int IDENTITY(1,1) PRIMARY KEY,
EmployeeName varchar(255) NOT NULL,
)

关于c# - 如何使用 LINQ 查找重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32255423/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com