Linq queries on a List<KeyValuePair<>>

P

pinkfloydfan

Hi there

I have got a bit stuck trying to extract some data from a
List<KeyValuePair<DateTime,Double>> and was hoping that someone could
help me out.

Is there a way using Linq to do the following tasks:

1) Extract a List<DateTime> of just the Keys?
2) Extract a List<Double> of just the Values?
3) Extract a List<Double> of just the Values but put in ascending
order of the Keys?

Thanks for any help

Lloyd
 
M

Marc Gravell

Well, I'd have to wonder why you don't just use Dictionary<,> /
SortedList<,> / SortedDictionary<,> (and just use .Keys and .Values)

But something like below:

List<KeyValuePair<DateTime, double>> list = null;
List<DateTime> keys = list.Select(x => x.Key).ToList();
List<double> values = list.Select(x => x.Value).ToList();
List<double> valuesByKey = list.OrderBy(x => x.Key)
.Select(x => x.Value).ToList();

You could also use the alternative LINQ syntax, but the above should work.

Marc
 
P

pinkfloydfan

That's great Marc thanks

I didn't originally use a Dictionary because there is no order
preserved in a Dictionary unlike a List. I've not come across a
SortedList or SortedDictionary before but I will look them up.

Cheers
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top