ceth
ceth

Reputation: 45295

Transform function to generic function

I have the functions that inserts entities to database. For example, one of them looks like:

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);
     }
 }

I would like to transform it to generic function, but I am not sure whet is the best way to pass the lambda function in the Where method.

Something like:

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);
     }
 }

Should I use delegates, lambdas or create this function as method of Entity class ?

Upvotes: 1

Views: 161

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11330

You could do something like:

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

Also, I would read the comment above. I don't think your asynchrony is set up quite right.

Upvotes: 1

Related Questions