Tech Off Thread

2 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Linq Max()

Back to Forum: Tech Off
  • User profile image

    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?


  • User profile image

    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!


Conversation locked

This conversation has been locked by the site admins. No new comments can be made.