gpt4 book ai didi

c# - 如何使用 linq 和 EntityFramework 获取对象的补充列表

转载 作者:行者123 更新时间:2023-11-30 14:25:42 24 4
gpt4 key购买 nike

我有两种类型,一种是另一种的缩减:

    public class A
{
public int ID { get; set; }

public string Name { get; set; }
}

public class B
{
public int ID { get; set; }

public string Name { get; set; }

public string Description { get; set; }
}

我有一个 List<A>称为 As这是由客户传递给我的,我有一个带有 DbSet<B> 的 EntityFramework DbContext称为 Bs .这两种类型可以在 ID 上进行匹配。

我要得到的是所有的As不在 Bs 中.你将如何在 Linq 中编写它?我正在尝试使用联接,但我似乎无法理解它。

在 T-SQL 中我会做这样的事情:

SELECT A.*
FROM A LEFT JOIN B
ON A.ID = B.ID
WHERE B.ID is NULL

最佳答案

你可以这样做:

List<A> As = ... //This is a list in memory

//Get all ids of As
var A_ids = As.Select(x => x.ID).ToList();

//Get all ids that are in both As (memory) and TableB (database)
//We put them in a HashSet for performance reasons
var ids_in_tableB_also =
new HashSet<int>(
db.TableB
.Where(x => A_ids.Contains(x.ID))
.Select(x => x.ID));

//Get the A objects that are in `As` but of which IDs are not in ids_in_tableB_also
//This operation would have been slower if we haven't used the HashSet above
var rest_of_As = As.Where(x => !ids_in_tableB_also.Contains(x.ID)).ToList();

关于c# - 如何使用 linq 和 EntityFramework 获取对象的补充列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37550603/

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