0

I'm new to LINQ and hoping someone can help me out writing this query to transform some data. I have a Dictionary<DateTime, string> containing data like this....

<01/07/12 00:00, "23,5,654,12,55,45,12,46,673,325,377,234,867,43,1,123,53,12,23,667,23,45,456,87">

<02/07/12 00:00, "22,63,567,13,64,6,4,64,7,2,5,234,667,787,326,234,64,24,5,76,23,556,77,34">

<03/07/12 00:00, "3,746,34,623,5,76,23,6,23,2,78,4,234,76,4,6,8,7,4,3,7645,23,34,6">

etc...

This dictionary has an Key which is a Date and a Value which is a CSV string containing 24 numbers (one for each hour of the day starting at 00:00). I would like to convert it into a Dictionary

<01/07/12 00:00, 23>

<01/07/12 01:00, 5>

<01/07/12 02:00, 654>

etc...

I've been trying for a while now a thought the answer lay in using SelectMany, but just can't get anything to work. I know I could just do it using some loops, but would really like to see a LINQ implementation.

Many thanks if you can help me. Colin.

1 Answer 1

3

How about this:

var dict = new Dictionary<DateTime, string>
{
    { new DateTime(2012, 7, 1), 
        "23,5,654,12,55,45,12,46,673,325,377,234,867,43,1,123,53,12,23,667,23,45,456,87" 
    },
    { new DateTime(2012, 7, 2), 
        "22,63,567,13,64,6,4,64,7,2,5,234,667,787,326,234,64,24,5,76,23,556,77,34" 
    }
};

dict.Select (d => d.Value.Split(new []{','})
    .Select ((v,i) => new {
        DateTime=d.Key.AddHours(i), Value=v}))
    .SelectMany (d => d)
    .ToDictionary (d => d.DateTime, d => int.Parse(d.Value));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.