使用Linq转换对象

时间:2011-01-28 00:39:27

标签: c# linq

我有这个类的对象列表:

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

我想将该DataPoints列表转换为此类对象的列表:

public class ChartSeries
{
    public string Name { get; set; }
    public List<uint> Values { get; set; }
}

以下是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 } }}}
};

我想将第一个列表转换为ChartSeries列表,如下所示:

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

如何使用Linq执行此操作?

1 个答案:

答案 0 :(得分:6)

在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()
        };