gpt4 book ai didi

c# - 使用泛型编写类似的逻辑

转载 作者:行者123 更新时间:2023-11-30 19:36:29 26 4
gpt4 key购买 nike

我有以下方法来确定我需要从数据库中删除哪些汽车。

private List<CarDTO> BuildCarsToDelete(IList<CarDTO> newCars, IList<CarDTO> existingCars)
{
var missingCars = new List<CarDTO>();

var cars = newCars.Select(c => c.CarId);
var newCarIds = new HashSet<int>(cars);

foreach (var car in existingCars)
{
//If there are no new cars then it had some and they have been removed
if (newCars.Count() == 0)
{
missingCars.Add(car);
}
else
{
if (!newCarIds.Contains(car.CarId))
{
missingCars.Add(car);
}
}
}

return missingCars;
}

这按我想要的方式工作 - 但如果我想为其他 DTO 的客户或公寓实现相同的功能,我将复制粘贴代码但只更改变量名称和周围的 DTO 类型 - 有更好的有可能使用泛型来保持算法和逻辑不变,但允许我在任何 DTO 上使用吗?

最佳答案

如果所有 id 都是 int 类型,那么您可以通过传入 Func 来确定 id。

private List<T> BuildToDelete<T>(
IList<T> newItems,
IList<T> existingItems,
Func<T, int> getId)
{
var missingItems = new List<T>();

var items = newItems.Select(getId);
var newItemIds = new HashSet<int>(items);

foreach (var item in existingItems)
{
if (newItems.Count() == 0)
{
missingItems.Add(item);
}
else
{
if (!newItemIds.Contains(getId(item)))
{
missingItems.Add(item);
}
}
}

return missingItems;
}

然后如下调用:

var results = BuildToDelete(newCars, existingCars, c => c.CarId);

关于c# - 使用泛型编写类似的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45306714/

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