简体   繁体   中英

c# object list filtering (linq?)

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM