MireaBackend/Endpoint/Sync/Common/DataRepository.cs

42 lines
955 B
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Mirea.Api.Endpoint.Sync.Common;
internal class DataRepository<T> where T : class
{
private readonly ConcurrentBag<T> _data = [];
private readonly object _lock = new();
public IEnumerable<T> GetAll() => _data.ToList();
public DataRepository(List<T> data)
{
foreach (var d in data)
_data.Add(d);
}
public T? Get(Func<T, bool> predicate)
{
var entity = _data.FirstOrDefault(predicate);
return entity;
}
public T Create(Func<T> createEntity)
{
var entity = createEntity();
_data.Add(entity);
return entity;
}
public T GetOrCreate(Func<T, bool> predicate, Func<T> createEntity)
{
lock (_lock)
{
var entity = Get(predicate);
return entity ?? Create(createEntity);
}
}
}