Data transfer object with O(1) lookup
Hi I want to use a datatransfer object that is got by reading a database using NHibenrate and that has like 1000 records and I need to use this DTo carefully wherein based on a certain key i select a value. My DTO will be seomthing like this.
public class DTO
{
string name;
int id;
int schoolId;
double value;
}
Now the problem is I get this as an enumerable.. Now from this enumerable based on the schoolid id and name i need to select a value which I do as of now as follows:
DtoList.Where(x=>x.name="name" && x.id=1 && x.schoolId=2).First();
Now the problem with this is it is an O(n) lookup and I want it to be O(1) which can be done by using an IDictionary.
I am wondering if I can make this DTO implement IDitcionary and then do the same. \
Is that possible? I think this is more from a c# perspective.
Also from an NHibernate perspective how this will work o开发者_开发技巧ut.
If you construct the list once and then look it up multiple times, maybe it's worth creating another object, which will consist of a dictionary, and create it from a collection of DTOs:
struct Key
{
string Name;
int Id;
int SchoolId;
}
class DictionaryObject
{
IDictionary<Key, double> _dict;
public DictionaryObject(IEnumerable<Dto> dtoList)
{
_dict = dtoList.ToDictionary(
o => new Key { Name = o.Name, Id = o.Id, SchoolId = o.SchoolId },
o => o.Value);
}
double GetValue(string Name, int Id, int SchoolId)
{
// if the key exists then...
return _dict[new Key { Name = Name, Id = Id, SchoolId = SchoolId }];
}
...
}
精彩评论