Search code examples
c#sortingkeyvaluepair

Sort List<KeyValuePair<string, double>> in c#


I'm developing a program that is reading csv-files and sort them values into a KeyValuePair-List.

private List<KeyValuePair<string, double>> SortValues(string[,] csvData)
    {
        var dateList = new List<String>();
        var valuesList = new List<double>();

        List<KeyValuePair<string, double>> valueList = new List<KeyValuePair<string, double>>();

        for (int i = 1; i < csvData.GetLength(0) - 1; i++)
        {
            String date = csvData[i, 1];
            String values = csvData[i, 14];

            date = date.Remove(0, 1);
            date = date.Remove(date.Length - 1, 1);

            values = values.Remove(0, 1);
            values = values.Remove(values.Length - 1, 1);

            dateList.Add(date);
            valuesList.Add(Double.Parse(values));

            valueList.Add(new KeyValuePair<string, Double>(date, Double.Parse(values)));

        }

        var result = valueList
            .GroupBy(r => r.Key)
            .Select(r => new KeyValuePair<string, double>(r.Key, r.Sum(p => p.Value)))
            .ToList();

        return result;
    }

My result is a big list of dates as string and currency values as double, like this:

{[29.03.19, EUR]}{[28.03.19, EUR]}{[27.03.19, EUR]}{[26.03.19, EUR]}{[25.03.19, EUR]}{[19.03.19, EUR]}{[18.03.19, EUR]}{[14.03.19, EUR]}{[12.03.19, EUR]}{[11.03.19, EUR]}{[08.03.19, EUR]}{[07.03.19, EUR]}{[06.03.19, EUR]}{[05.03.19, EUR]}{[04.03.19, EUR]}{[01.03.19, EUR]}{[28.02.19, EUR]}{[27.02.19, EUR]}{[26.02.19, EUR]}{[19.02.19, EUR]}{[12.02.19, EUR]}{[11.02.19, EUR]}{[07.02.19, EUR]}{[05.02.19, EUR]}{[04.02.19, EUR]}{[01.02.19, EUR]}

My problem is to split these KeyValuePair-List into seperate lists for every month.

For example: I want to extract only all "KeyValuePairs" for the second month and write them into a seperate KeyValuePair-List.


Solution

  • This should give you a Dictionary where the two character string representation of the months are the Key:

    SortValues(input).GroupBy(value => value.Key.Substring(3, 2)).ToDictionary(group => group.Key, group => group.ToArray());
    

    Feel free to parse the months in a little more elegant way, I figured that part was beside the point of what you're looking for.

    If you'd like to utilize the deferred loading of LINQ, you could replace ToArray() with Select(_ => _). Both are just a way of getting the IEnumerable<KeyValuePair<string,double>> out of the IGrouping object that GroupBy gives you.