开发者

LINQ from SortedList C#

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开发者_JS百科 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?


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);


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");


What about

normalList = sortedList.Items;

Does that give you the list you want?


To answer the question "Is there a better way to convert my SortedList to List<> (I'm not bothered about preserving the key)?"... Here is example, with last line as the answer, resulting in list with integers 4, 1, 3, 2:

SortedList<string,int> sortedList = new SortedList<string,int>();
sortedList.Add("One", 1);
sortedList.Add("Two", 2);
sortedList.Add("Three", 3);
sortedList.Add("Four", 4);
List<int> list = sortedList.Values.ToList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜