Reputation: 1036
I have a list of objects IEnumerable<Item>
, lets call it Items. Item has a propoerty Item.Subitems
which is a list of subitems. List is about 500 items, with avg 10 subitems each.
Those are all "in memory" objects (theres no db querying at this level).
I would like to have a function:
public static string GetSubitemValue( int id )
{
return Items.SelectMany( i => i.Subitems ).FirstOrDefault( si => si.id == id).Value;
}
function GetSubitemValue
will be called multiple times (lets assume 500) during one process call (this a part o Razor view rendering process).
Are there any build-in linq enhancements that would support repeatable list search (iteration?). Should i care to do some caching or indexing on my own?
Upvotes: 2
Views: 137
Reputation: 17595
To my knowledge there is no built-in mechanic to enhance multiple sorts. However, you could implement caching of return values as follows.
private static Dictionary<int,string> Cache = new Dictionary<int,string>();
public static string GetSubitemValue(int id)
{
if (!Dictionary.Contains(id))
{
Dictionary[id]
= Items.SelectMany(i => i.Subitems)
.FirstOrDefault(si => si.id == id).Value;
}
return Dictionary[id];
}
However, note that your initial code snippet throws an exception if Items
does not contain the desired id.
Upvotes: 4