开发者

Converting data from discrete properties of objects in an IEnumerable into an array/series for charting?

开发者 https://www.devze.com 2023-04-10 14:48 出处:网络
I 开发者_高级运维have an IEnumerable (List<>) of a particular Type.The Type has a set of properties which I would like to chart as individual series (MVC3/Razor).

I 开发者_高级运维have an IEnumerable (List<>) of a particular Type. The Type has a set of properties which I would like to chart as individual series (MVC3/Razor).

Is there a way I can transpose the data in the list of objects into a list of the properties?

e.g. Given the code below, the end result I am trying to acheive is a set of Series so I have

Bucket1: IEnumerable<Date, Value>
Bucket2: IEnumerable<Date, Value>
etc

So that I can then chart each series to get a line chart with Date on x and value on y, for (in this example) 3 series/lines. This code works perfectly, but just feels wrong somehow?

 var buckets = new List<Bucket>(){
            new Bucket{
                    Date=DateTime.Today.AddDays(-3),
                    Bucket1=1000,
                    Bucket2=2000,
                    Bucket3=3000},
                new Bucket{
                    Date=DateTime.Today.AddDays(-2),
                    Bucket1=1000,
                    Bucket2=2020,
                    Bucket3=3300},
                new Bucket{
                    Date=DateTime.Today.AddDays(-1),
                    Bucket1=1000,
                    Bucket2=2040,
                    Bucket3=3600}
        };

        var chart = new Chart(){ Height = 400, Width = 600 };
        var area = new ChartArea();
        chart.ChartAreas.Add(area);

        var series1 = chart.Series.Add("Bucket 1");
        var series2 = chart.Series.Add("Bucket 2");
        var series3 = chart.Series.Add("Bucket 3");
        foreach (var series in chart.Series)
        {
            series.ChartType = SeriesChartType.Line;
        }

        foreach (var item in buckets)
        {
            series1.Points.AddXY(item.Date, item.Bucket1);
            series2.Points.AddXY(item.Date, item.Bucket2);
            series3.Points.AddXY(item.Date, item.Bucket3);
        }


What about just using a Lambda expression for each serie (code below was not tested - it's just a prototype):

var series1 = buckets.Select(b => new { b.Date, b.Bucket1 });
var series2 = buckets.Select(b => new { b.Date, b.Bucket2 });


Thanks to the comments posted I kept my original code and don't think there's an easier way to do this.

0

精彩评论

暂无评论...
验证码 换一张
取 消