作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下方法来确定我需要从数据库中删除哪些汽车。
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/
我是一名优秀的程序员,十分优秀!