Question

Silly if you ask me. But this message is here because I will assume (probably correctly) that I am the silly one, not Microsoft. So... is there something I'm missing? Why didn't they include a "Find" method to this baby? The find could work on the Values, which are objects, so then I could do this:

someObject = SortedList.Values.Find(order => order.OrderID == orderID);
Was it helpful?

Solution

You might be looking for .First(...) or .Single(...) (or their OrDefault variants) in LINQ, but that only really works well with types that implement IEnumerable<T>. A SortedList is not strongly typed, hence the Lambda won't work. Have a look at LINQ's .Cast<T>().

OTHER TIPS

You probably want:

SortedList.Values.Cast<Order>().FirstOrDefault(order => order.OrderID == orderID);

Of couse, if you are talking about SortedList<TKey, TValue>, the call to Cast() is unnecessary.

Btw, if you are poking through the Values of a SortedList in that manner, there is a good chance you're using a poor choice for the key / using the wrong data-structure altogether.

EDIT:

If you can't use LINQ in the project, nor do you wish to maintain separate data-structures keyed by the order's date and orderID respectively (as suggested by Ben Voigt), I see no choice but to implement the search yourself:

foreach(ShopOrder order in sortedList.Values)
{
  if(order.OrderID == orderID) return order;
}

return null; // or throw an exception, whichever you find appropriate.

If you want to generalize further, write your own FirstOrDefault implementation.

Are you searching on the same field that the list is sorted by? A binary search would be fastest, and SortedList provides the IndexOfKey function to do that.

It looks like you're searching through the values, in which case using LINQ's FirstOrDefault on the result of GetValueList should work.

See also: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/55241049-7e7e-4006-8e04-70779698d609

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top