Using Linq to transform objects
I have a list 开发者_开发技巧of objects of this class:
public class DataPoint
{
public class Item
{
public string name { get; set; }
public int total { get; set; }
}
public List<Item> Items { get; set; }
public DateTime Date { get; set; }
}
I want to convert that list of DataPoints into a list of objects of this class:
public class ChartSeries
{
public string Name { get; set; }
public List<uint> Values { get; set; }
}
Here is an explicit example of the list of DataPoints
IEnumerable<DataPoint> data = new List<DataPoint>() {
new DataPoint() { date = DateTime.Today.AddDays(-4), Items = new List<DataPoint.Item>() {new DataPoint.Item() {name="Pirates", total=90 } , {new DataPoint.Item() {name="Buccaneers", total=20 } }}},
new DataPoint() { date = DateTime.Today.AddDays(-3), Items = new List<DataPoint.Item>() {new DataPoint.Item() {name="Pirates", total=80 } , {new DataPoint.Item() {name="Buccaneers", total=19 } }}},
new DataPoint() { date = DateTime.Today.AddDays(-2), Items = new List<DataPoint.Item>() {new DataPoint.Item() {name="Pirates", total=70 } , {new DataPoint.Item() {name="Buccaneers", total=18 } }}},
new DataPoint() { date = DateTime.Today.AddDays(-1), Items = new List<DataPoint.Item>() {new DataPoint.Item() {name="Pirates", total=60 } , {new DataPoint.Item() {name="Buccaneers", total=17 } }}},
new DataPoint() { date = DateTime.Today.AddDays(-0), Items = new List<DataPoint.Item>() {new DataPoint.Item() {name="Pirates", total=50 } , {new DataPoint.Item() {name="Buccaneers", total=16 } }}}
};
I want to convert that first list into a list of ChartSeries that would look like this:
IEnumerable<ChartSeries> series = new List<ChartSeries>() {
new ChartSeries() { Name = "Pirates", Values = new List<uint>() { 90, 80, 70, 60, 50} },
new ChartSeries() { Name = "Buccaneers", Values = new List<uint>() { 20, 19, 18, 17, 16} },
};
How can I do this with Linq?
Tested in LINQPad:
var q = from d in data
from i in d.Items
group i by i.name into g
select new ChartSeries{
Name = g.Key,
Values = g.Select(i => (uint)i.total).ToList()
};
精彩评论