将函数转换为泛型函数

时间:2015-03-16 16:49:47

标签: c# generics

我有将实体插入数据库的功能。例如,其中一个看起来像:

public async void InsertInspections(ObservableCollection<Inspections> inspections)
{
    _connection.CreateTableAsync<Inspections>().Wait();

    foreach (var inspection in inspections)
    {
        var task = _connection.Table<Inspections>().
                   Where(v => v.InspectionId == inspection.InspectionId).ToListAsync();
         task.Wait();

         if (task.Result.Any()) 
             _connection.UpdateAsync(inspection);
         else
             _connection.InsertAsync(inspection);
     }
 }

我想将它转换为泛型函数,但我不确定这是在Where方法中传递lambda函数的最佳方法。

类似的东西:

public async void InsertEntities<T>(ObservableCollection<T> entities)
{
    _connection.CreateTableAsync<T>().Wait();

    foreach (var entity in entities)
    {
        var task = _connection.Table<T>().
                   // what is the best way to pass this function to the method ???
                   Where(v => v.InspectionId == entity.InspectionId).ToListAsync();
         task.Wait();

         if (task.Result.Any()) 
             _connection.UpdateAsync(entity);
         else
             _connection.InsertAsync(entity);
     }
 }

我应该使用delegates,lambdas还是创建此函数作为Entity类的方法?

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

InsertEntities<T>(ObservableCollection<T> entities, Func<T, bool> exp)
.Where(exp)

另外,我会阅读上面的评论。我不认为你的异步设置得恰到好处。