Select highest value for the key in dictionary that is highest among the keys lower than given "at" value

StackOverflow https://stackoverflow.com/questions/23629749

  •  21-07-2023
  •  | 
  •  

سؤال

Is there a better way of writing this, with LINQ instead of custom method. Sorted Dictionary is not an option. I think that Dictionary.Where(x => x.Key < at) is fine but .OrderBy(x => x.Key).Last() will be slow, as I need only one value I am wasting CPU for ordering.

Dictionary.Where(x => x.Key < at).OrderBy(x => x.Key).Last().Value;

maybe:

Dictionary[Dictionary.Where(x => x.Key < at).Max(x => x.Key)];
هل كانت مفيدة؟

المحلول

The second option is good. It first finds the max Key and then the Value that goes with it. Alternatively, you could write a MaxBy method. Or just use the one already implemented in MoreLinq: http://code.google.com/p/morelinq/

نصائح أخرى

Dictionary[Dictionary.Keys.Where(key=> key < at).Max()]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top