Tech Off Thread

2 posts

Linq Max()

Back to Forum: Tech Off
  • User profile image
    phreaks

    string keyword = "michio kaku";
    using (MyModelEntities db = new MyModelEntities()) 
    {        
            long? maxId = db.ResultDatas.Select(m => m.Query == Keyword).Max(m => db.ResultDatas.Max(r => r.ResultId)); 
    }

    In the code above, I have an Entity Set named "ResultDatas" with some fields "Query" and "ResultId".

    The underlying data store could have 0 to n matches for a given query. I want to return the max(ResultId) of the matched keyword (or null for non-matched sets).

    The code above works, but seems ineffecient, can someone explain a better way to do this?

    TIA

  • User profile image
    phreaks

    Turns out the query I was using above was completly wrong to begin with.

    long? maxId = db.ResultDatas.Where(model => model.Query == Keyword).Max(res => (long?)res.ResultId) ?? 0;
    
    

    The above code works, is intuitive and seems to be reasonably performant.

    If anyone knows any better please let me know!

     

Comments closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.