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