1

How can I get RSI_Value in the rsi_Wilder by the IdDate? I sort my rsi_Wilder, so the highest IdDate always will be the last index. Therefore I can do this:

class RSI
{
    public int IdDate { get; set; }
    public decimal RSI_Value { get; set; }
}

List<Datamodel.RSI> rsi_Wilder = BeregnRsi_Wilder(idVirksomhedensStamdata, BeregnAntalDage: 21);
var lastValue = rsi_Wilder[rsi_Wilder.Count - 1].RSI_Value;

It works fine, but I think there must be a better way/better performance to find to RSI_Value by the highest IdDate. What's the best way to do this?

EDIT: Example.

rsi_wilder.Add(new Datamodel.RSI{IdDate = 25, RSI_Value = 17});
rsi_wilder.Add(new Datamodel.RSI{IdDate = 26, RSI_Value = 26});
rsi_wilder.Add(new Datamodel.RSI{IdDate = 27, RSI_Value = 9});
rsi_wilder.Add(new Datamodel.RSI{IdDate = 31, RSI_Value = 70});
rsi_wilder.Add(new Datamodel.RSI{IdDate = 32, RSI_Value = 55});

I need to get the RSI_Value with the highest IdDate and I don't know the IdDate number. The result I seek is RSI_Value = 55. The code var lastValue = rsi_Wilder[rsi_Wilder.Count - 1].RSI_Value; do the job, because the IdDate in rsi_Wilder is sorted from lowest to highest number.

MHP
  • 81
  • 1
  • 10

3 Answers3

3

Ordering the entire sequence costs O(n*log(n)), and it's not really needed if all you want is the max of your collection.

You can find the max in O(n) just by iterating over the sequence, and keeping track of the maximum element that you have encountered. You might even create an extension method to do it for you, or just do it using LINQ:

var result = yourcollection.Aggregate((x,y) => x.IdDate > y.IdDate ? x : y);

you can find many more examples here

Community
  • 1
  • 1
Save
  • 11,450
  • 1
  • 18
  • 23
  • Was about to post an answer similar to this, due to that O(n) would be the most effective. Upvoted! – Bauss Jul 23 '15 at 18:55
2
using System.Linq;

var lastValue = rsi_Wilder.Max(x => x.RSI_Value);
Kevin
  • 151
  • 3
  • 11
  • According to his description, he wants the max RSI_Value by IdDate; this just returns the max RSI_Value. – Save Jul 23 '15 at 19:10
  • I can not use rsi_Wilder.Max(x => x.RSI_Value); it should be something like this rsi_Wilder.Max(x => x.Id_Date).select(x => x.RSI_Value); of course it is not going to work. – MHP Jul 23 '15 at 19:16
-1
decimal rsiValueOfHighestId =
    rsi_Wilder.OrderByDescending(rsi => rsi.IdDate).First().RSI_Value;
Jashaszun
  • 9,207
  • 3
  • 29
  • 57