gpt4 book ai didi

c# - 使用 Lambda 删除重复项

转载 作者:行者123 更新时间:2023-11-30 20:55:39 25 4
gpt4 key购买 nike

我需要一些帮助来使用 lambda 表达式删除 Entity Framework 上下文中的重复条目。我有一个包含以下列的表格:

Id、DateOfIncident、Description、EmployeeId、IncidentTypeId 和 IsAttendanceIncident

我想删除 DateOfIncident、EmployeeID、IncidentTypeID 和 IsAttendanceIncident 相同的重复条目。 我确实想保留一个条目。我知道如何在 SQL 中使用带有 CTE 的存储过程来执行此操作,但我不知道如何使用 Lambda 表达式来完成此任务。

此代码返回一个不包括我的重复项的列表,但现在我该如何删除不在该列表中的那些重复项?

  var query = db.Incidents.Where(x => x.IsAttendanceIncident == "Y").GroupBy(x => new { x.EmployeeId, x.DateOfIncident, x.IsAttendanceIncident })
.Select(x => x.FirstOrDefault());

更新:

所以我继续编写自定义 IEqualityComparer。现在,如何使用 id 删除上下文中不在 distinctItems 中的事件?

 static void Main(string[] args)
{
DALIncidents.AttendanceEntities1 db = new DALIncidents.AttendanceEntities1();

IEnumerable<DALIncidents.Incident> distinctItems = db.Incidents.Where(c => c.IsAttendanceIncident == "Y");
distinctItems = distinctItems.Distinct(new DALIncidents.DistinctIncidentComparer());

Console.ReadLine();
}

最佳答案

var query = db.Incidents
.Where(x => x.IsAttendanceIncident == "Y")
.GroupBy(x => new { x.EmployeeId, x.DateOfIncident, x.IsAttendanceIncident })

示例 1:

    .Select(x => x.FirstOrDefault());  // your original code which retrieves entities to not delete

var dupes = db.Incidents.Except( query ); // get entities to delete

示例 2:

    .SelectMany( x => x.OrderBy( y => y.Id ).Skip(1) ); // gets dupes directly

var dupes = query; // already have what we need

最后:

foreach( var dupe in dupes )
{
db.Incidents.Remove( dupe );
}

从我之前使用的测试上下文生成的示例 SQL,其中 Person 实体与 watches 具有 1:N 关系:

C#:

context.Persons.SelectMany(x => x.Watches.OrderBy(y => y.Id).Skip(1))

生成的 SQL:

SELECT 
1 AS [C1],
[Skip1].[Id] AS [Id],
[Skip1].[Brand] AS [Brand],
[Skip1].[Person_Id] AS [Person_Id]
FROM [dbo].[Persons] AS [Extent1]
CROSS APPLY (SELECT [Project1].[Id] AS [Id], [Project1].[Brand] AS [Brand], [Project1].[Person_Id] AS [Person_Id]
FROM ( SELECT [Project1].[Id] AS [Id], [Project1].[Brand] AS [Brand], [Project1].[Person_Id] AS [Person_Id], row_number() OVER (ORDER BY [Project1].[Id] ASC) AS [row_number]
FROM ( SELECT
[Extent2].[Id] AS [Id],
[Extent2].[Brand] AS [Brand],
[Extent2].[Person_Id] AS [Person_Id]
FROM [dbo].[Watches] AS [Extent2]
WHERE [Extent1].[Id] = [Extent2].[Person_Id]
) AS [Project1]
) AS [Project1]
WHERE [Project1].[row_number] > 1 ) AS [Skip1]

关于c# - 使用 Lambda 删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18186843/

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