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

标签 c# .net generics

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

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/

相关文章:

c# - 如何将 "Add"两个字节放在一起

c# - 如何配置 Fluent NHibernate 以将查询输出到 Trace 或 Debug 而不是控制台?

c# - 搜索特定字符串的文件并检查之后是否有任何内容

xcode - 非泛型 Swift 类可以实现 UIPickerViewDataSource 但泛型版本不能

java - 向 Mockito.any() 提供类以使 verify() 调用明确的正确语法是什么?

c# - 获取 Google 凭据抛出未处理的异常

c# - MembershipUser 和 Entity Framework 代码优先

c# - 无法在 WCF Rest 中获取未定义或空引用的属性 'appendChild'

.net - 什么时候必须使用绑定(bind)重定向?

java - 使用奇怪的泛型覆盖 java 方法中的错误