Raaz Raaz - 3 months ago 12
C# Question

shift content of a dictionary by specified size to a new dictionary in C# LInq

I am looking for a help in C#, LINQ to write a method that accepts a dictionary and integer (shifting size)

and returns another dictionary with all values shifted to right by the size specified.
here is the example.
the dictionary looks like this;

01/01/2015 --- 100
02/01/2015 --- 150
03/01/2015 --- 200


Code:

IDictionary<DateTime, int> inputDic = new Dictionary<DateTime, int>();
inputDic.Add(new DateTime(2015, 01, 01), 100);
inputDic.Add(new DateTime(2015, 02, 01), 150);
inputDic.Add(new DateTime(2015, 03, 01), 200);

public static IDictionary<DateTime, int> ShiftContent(
this IDictionary<DateTime, int> inputDictionary, int size)
{
//shifting logic;
return outputDictionary;

}


So if the size is 2, the output dictionary should contain values as below; below dates are in mm/dd/yyyy.

01/01/2015 --- 0
02/01/2015 --- 0
03/01/2015 --- 100
04/01/2015 --- 150
05/01/2015 --- 200


Any help is greatly appreciated.

Answer

This is yet another way only using only one linq query :

public static IDictionary<DateTime, int> ShiftContent(
        this IDictionary<DateTime, int> inputDictionary, int size)
{       
    return 
        Enumerable.Range(1, size).Select(value => new KeyValuePair<DateTime, int>(inputDictionary.First().Key.AddMonths(value - 1), 0))     
        .Union(inputDictionary.ToList().Select(value => new KeyValuePair<DateTime, int>(value.Key.AddMonths(size), value.Value)))
        .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
Comments