I’m working on a problem in C# 2.0/.NET 2.0 where I have a Sortedlist and want to search all the ‘values’ (not the ‘keys’) of this SortedList for a certain substring and count up how many occurrences there are.
This is what I’m trying to do:
{ Sortedlist<string,string> mySortedList; // some code that instantiates mySortedList and populates it with data List<string> myValues = mySortedList.Values; // <== does not work int namesFound = myValues.FindAll(ByName(someName)).Count; }
Naturally, this doesn’t work because mySortedList.Values returns an IList, while ‘myValues’ is a List. I tried ‘casting’ the IList so that it would be accepted by myValues, but it doesn’t seem to work.
Of course, I can loop over mySortedList.Values in a ‘foreach’ loop, but I don’t really want to do this.
Anyone have any suggestions?
EDIT-1: Ok, well it looks like there isn’t a native way to do this easily. I had assumed that I was just missing something, but apparently I’m not. So I guess I’m just going to do a ‘foreach’ over the IList.
Thanks for the feedback everyone! I voted everyone up 1 because I thought all the feedback was good. Thanks again! 🙂
EDIT-2: Looks like CMS has the answer I was looking for. The only caveat with this (as Qwertie pointed out) is that there is a potential performance penalty since it involves copying all the values to another List and then searching that list start-to-finish. So for short lists, this answer is effective. Longer lists? well that’s up to you to decide…
Since the IList Interface implements IEnumerable, you can actually get a
List<T>of values using theList<T> (IEnumerable) Constructor: