簡體   English   中英

Linq查詢將數據轉換為時間序列

[英]Linq query to transform data into timeseries

我有以下數據:

10/6/2018 - Category 1
11/6/2018 - Category 1
12/6/2018 - Category 2
13/6/2018 - Category 1
15/6/2018 - Category 3
20/7/2018 - Category 1
21/7/2018 - Category 1
4/8/2018 - Category 4
5/8/2018 - Category 2

我試圖在點網核心中使用linq,以獲得可以繪制的json結果。 我正在嘗試制作一個按月分組計數的圖表。

結果應如下所示(類別是動態的,我無法對其進行硬編碼):

series: [{
  name: 'Category 1',
  data: [3, 2, 0]
}, {
  name: 'Category 2',
  data: [1, 0, 1]
}, {
  name: 'Category 3',
  data: [1, 0, 0]
}, {
  name: 'Category 4',
  data: [0, 0, 1]
}]

我不確定從哪里開始,如何在Linq的點網核心中做到這一點

根據評論進行編輯:

首先,數據來自數據庫,因此它是動態的。 其次,結果是我希望輸出的結果,即類別1在6月有2個項目,在7月有2個項目,在8月有0個項目(如果不清楚,我使用DD / MM / YYYY)

您可以使用NewtonSoft.Json將其作為JSON進行獲取:

void Main()
{
    var myData = new List<MyClass> {
        new MyClass {Date=new DateTime(2018,6,10),Category="Category 1"},
        new MyClass {Date=new DateTime(2018,6,11),Category="Category 1"},
        new MyClass {Date=new DateTime(2018,6,12),Category="Category 2"},
        new MyClass {Date=new DateTime(2018,6,13),Category="Category 1"},
        new MyClass {Date=new DateTime(2018,6,15),Category="Category 3"},
        new MyClass {Date=new DateTime(2018,7,20),Category="Category 1"},
        new MyClass {Date=new DateTime(2018,7,21),Category="Category 1"},
        new MyClass {Date=new DateTime(2018,8,4),Category="Category 4"},
        new MyClass {Date=new DateTime(2018,8,5),Category="Category 2"},
    };


    var result = from c in myData.Select(d => d.Category).Distinct()
                 let months = myData.Select(d => d.Date.Month).Distinct().OrderBy(d => d).ToArray()
                 let m1 = months[0]
                 let m2 = months[1]
                 let m3 = months[2]
                 select new {
                     name = c,
                     data = new int[] {
                        myData.Count(d => d.Category == c && d.Date.Month==m1),
                        myData.Count(d => d.Category == c && d.Date.Month==m2),
                        myData.Count(d => d.Category == c && d.Date.Month==m3),
                     }
                 };

    var json = JsonConvert.SerializeObject(result, Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(@"""series"": " + json);
}

public class MyClass
{
    public DateTime Date { get; set; }
    public string Category { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM