简体   繁体   中英

convert Dictionary<string, myClass> to List<double[]> using c# linq

I have a dictionary of <string,Rate>

where Rate is defined as:

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;}
}

I wish to convert this dictionary to List where the List is broken up (grouped by) Tier from Rate above and the double array holds the Values from Rate as well.

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

so if..

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)

then myList[0] would countain 1.1 and 2.2, and myList[1] would countain 3.3.

Answers were good but I need to modify question to provide the list sorted by the tier.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM