views:

453

answers:

2

I'm fairly new to C#, and completely new to LINQ.

I have an existing object of type SortedList, which I would like to filter through using LINQ. However I appear to be having issues with this, apparently as the SortedList type is not generic.

For the timebeing I've looped through the entire SortedList and manually added the objects within to a List and used LINQ to filter from there. However, that seems to me, well, rubbish.

Is there a better way to convert my SortedList to List<> (I'm not bothered about preserving the key)? Or indeed to convert my SortedList to SortedList<> perhaps?

+1  A: 

Original SortedList class is part of Collection. Generics introduces SortedList but if you have old code, then it wont be using that.

The easiest is to use the Cast method or OfType extension method that is made available for SortedList. Those methods will give you IEnumerable list that you can apply generic Linq operations. Make sure you include using System.Linq; in the beginning then you should be able to do like below:

sortedList.Cast<int>().Where(i=>i > 5);
sortedList.OfType<Car>().Where(c=> c.Color == Color.Blue);
Fadrian Sudaman
I don't believe DictionaryEntry can be cast to int; you will need to specify either Keys or Values.
Si
The above is just an example, you can cast it to anything that say fit. What it says in the example above is cast the SortedList collection into an IEnumerable<int> (or whatever you like by replacing the int to yourType) and of course the casting will fail if type doesnt match. The specification for the method is Cast<T> where T is a parameterized type
Fadrian Sudaman
A: 

If you don't need to filter by Keys, just cast and filter on Values

SortedList sl = new SortedList();
sl.Add("foo", "baa");
var baas = sl.Values.Cast<string>().Where(s => s == "baa");
Si