使用c#linq </double []> </string,>将Dictionary <string,myclass =“”>转换为List <double []>

时间:2013-04-01 17:03:31

标签: c# linq list dictionary group-by

我有<string,Rate>

字典

其中Rate定义为:

class Rate
{
  public string Name { get; set;}
  public int Tier{ get; set;}
  public double Value { get; set;}

  public Rate(string name,int tr,double val)
   { Name = name; Tier = tr; Value = val;}
}

我希望将此字典转换为列表,其中列表被分解(按照上面的速率分组),并且双数组也保持从速率的值。

Rate rate1 = new Rate("One",1,1.1);
Rate rate2 = new Rate("Two",1,2.2);
Rate rate3 = new Rate("Three",2,3.3);

所以如果..

Dictionary<string,Rate> rates = new Dictionary<string,Rate> { {rate1.Name,rate1},{rate2.Name,rate2},{rate3.Name,rate3}};


List<double[]> myList = (linq result from Rates separated list of arrays by tier)

然后myList [0]将计算1.1和2.2,myList [1]将计算3.3。

答案很好但我需要修改问题以提供按层排序的列表。

2 个答案:

答案 0 :(得分:3)

List<double[]> list = rates
            .GroupBy(pair => pair.Value.Class, pair => pair.Value.Value)
            .Select(doubles => doubles.Select(d => d).ToArray())
            .ToList();

答案 1 :(得分:1)

List<double[]> myList = rates.GroupBy(p => p.Value.Tier)
                             .Select(g => g.Select(p => p.Value.Value).ToArray())
                             .ToList();