By efficient I mean shortest time for computation.
I came up with:
List<float> valuesLaterThanDate = new List<float>();
foreach (var kvp in sortedList.Where( t => t.Key >= selectionDate))
{
valuesLaterThanDate.Add( kvp.Value );
}
is there a more efficient way? Or more compact expression?
CodePudding user response:
Yes, you can write it as a more compact expression:
var valuesLaterThanDate = sortedList.Where(t => t.Key >= selectionDate).Select(t => t.Value).ToList();
CodePudding user response:
There are two performance efficiencies you can make:
- Use
IndexOfKey
to perform a binary search of the starting key. This hasO(log(N))
efficency. - You can pre-allocate the list to do a more efficient insert.
var startIndex = sortedList.IndexOfKey(selectionDate);
var valuesLaterThanDate = new List<float>(sortedList.Count - startIndex);
for (var i = startIndex; i < sortedList.Count; i )
{
valuesLaterThanDate.Add(sortedList[i].Value);
}
Note that IndexOfKey
just returns -1
if the key is not found, so if that can happen then you may need to implement binary search yourself. There have been complaints about this issue in the past regarding SortedList<T>
.
CodePudding user response:
A more efficient way? This is not answerable, as you have not laid out any the criteria to measure/determine efficiency. Performance efficiency? Memory usage efficiency? Code readability/maintainability?
A more compact form? Yes:
var valuesLaterThanDate = sortedList
.Where(t => t.Key >= selectionDate)
.Select(t => t.Value)
.ToList();