Build a Simple In-Memory Database with?
Search
Real World Need
In-memory data storage is useful when:
- High performance is required
- Offline data handling is needed
- Unit testing should not depend on a real database
- Temporary storage is required during processing
Concept
Store objects in memory and allow querying like a lightweight database.
Implementation
public class InMemoryDb<T>
{
private readonly List<T> _data = new List<T>();
public void Add(T item) => _data.Add(item);
public IEnumerable<T> Get(Func<T, bool> predicate)
=> _data.Where(predicate);
}
// Usage
var db = new InMemoryDb<Employee>();
db.Add(new Employee { Id = 1, Name = "Sandeep" });
var result = db.Get(e => e.Name.Contains("San"));
Key Concepts
- Generic in-memory storage
- Predicate-based querying
- Not thread-safe unless synchronization is added