using System.Collections.Generic;
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public override string ToString()
return string.Format("{0} {1}, age {2}", FirstName, LastName, Age);
private static Random _random = new Random((int)DateTime.Now.Ticks);
private static string[] _firstNames = new string[]
private static string[] _lastNames = new string[]
public IEnumerable<DbEntity> GetSequence(int count)
for (int i = 0; i < count; i++)
yield return new DbEntity
FirstName = _firstNames[_random.Next(_firstNames.Length - 1)],
LastName = _lastNames[_random.Next(_lastNames.Length - 1)],
Age = _random.Next(18, 60)
public IEnumerable<DbEntity> GetSequence()
yield return new DbEntity
FirstName = _firstNames[_random.Next(_firstNames.Length - 1)],
LastName = _lastNames[_random.Next(_lastNames.Length - 1)],
Age = _random.Next(18, 60)
public struct FirstLastKey
private readonly string _firstName;
private readonly string _lastName;
public FirstLastKey(string firstName, string lastName)
public override bool Equals(object obj)
var objValue = (FirstLastKey)obj;
if(this._firstName == objValue._firstName && this._lastName == objValue._lastName)
public override int GetHashCode()
return (this._firstName.GetHashCode() >> 4) & this._lastName.GetHashCode();
private readonly int _age;
public override bool Equals(object obj)
var objValue = (AgeKey)obj;
return this._age == objValue._age;
public override int GetHashCode()
private readonly List<DbEntity> _entities = new List<DbEntity>();
private readonly Dictionary<FirstLastKey, List<DbEntity>> _fnDict = new Dictionary<FirstLastKey, List<DbEntity>>();
private readonly Dictionary<AgeKey, List<DbEntity>> _ageKeyDict = new Dictionary<AgeKey, List<DbEntity>>();
public void AddRange(IEnumerable<DbEntity> entities)
_entities.AddRange(entities);
foreach(var item in entities)
var firstLastKey = new FirstLastKey(item.FirstName, item.LastName);
var ageKey = new AgeKey(item.Age);
if(_fnDict.ContainsKey(firstLastKey))
_fnDict[firstLastKey].Add(item);
_fnDict.Add(firstLastKey, new List<DbEntity>() { item });
if(_ageKeyDict.ContainsKey(ageKey))
_ageKeyDict[ageKey].Add(item);
_ageKeyDict.Add(ageKey, new List<DbEntity>() { item });
public IList<DbEntity> FindBy(string firstName, string lastName)
var key = new FirstLastKey(firstName, lastName);
if(_fnDict.ContainsKey(key))
return new DbEntity[] { };
public IList<DbEntity> FindBy(int age)
var key = new AgeKey(age);
if(_ageKeyDict.ContainsKey(key))
return new DbEntity[] { };
public static void Main()
var dbGenerator = new DbGenerator();
db.AddRange(dbGenerator.GetSequence(10000));
var items = db.FindBy("Jack", "Jones");
Console.WriteLine(items.Count);
var items2 = db.FindBy(30);
Console.WriteLine(items2.Count);