代码之家  ›  专栏  ›  技术社区  ›  LG3

在Linq select中更改查询之外的值

  •  1
  • LG3  · 技术社区  · 3 年前

    这有点脱离了数据主题,但我一直很难弄清楚如何做到这一点。我有一个图表控件,它为每个图表部分使用颜色。我想为我的图表指定恒定的颜色,这样它们就不会随机生成。

    以下是我的linq查询:

    private void PopulateChart()
    {
      IEnumerable<ISeries> result = this.DataRecords
            .Where(w => w.TimeNow.Date == this.SelectedDate.Date)
            .GroupBy(g => g.Running)
            .Select(item => new PieSeries<double>
            {
              Values = new List<double> { item.Sum(x => x.Elapsed) },
              Name = item.Key ? "On" : "Off",
              Stroke = null,
              Fill = new SolidColorPaint(SKColors.Yellow)
            });
    
      this.ChartSeries = new ObservableCollection<ISeries>(result);
    }
    

    现在我的颜色总是黄色= SKColors.Yellow .我怎样才能做出一系列的颜色。例如 SKColors。黄的 SKColors.Blue 然后在我的Select中使用它们来为每个部分传递它们?

    下面是一个数组示例:

    private void PopulateChart()
    {
      SKColor[] colors = { SKColors.Yellow, SKColors.Blue };
    
      IEnumerable<ISeries> result = this.DataRecords
            .Where(w => w.TimeNow.Date == this.SelectedDate.Date)
            .GroupBy(g => g.Running)
            .Select(item => new PieSeries<double>
            {
              Values = new List<double> { item.Sum(x => x.Elapsed) },
              Name = item.Key ? "On" : "Off",
              Stroke = null,
              Fill = new SolidColorPaint(colors[0])
            });
    
      this.ChartSeries = new ObservableCollection<ISeries>(result);
    }
    

    所以问题是如何通过0,然后通过1 colors[0] ?

    1 回复  |  直到 3 年前
        1
  •  1
  •   D-Shih    3 年前

    我们可以尝试使用 Select 重载方法,可以通过 当前迭代中的索引号

    应用于每个源元素的变换函数;函数的第二个参数表示源元素的索引。

    然后我们可以尝试使用mod( % )通过索引号来确保 Yellow 另一个是 Blue

      IEnumerable<ISeries> result = this.DataRecords
            .Where(w => w.TimeNow.Date == this.SelectedDate.Date)
            .GroupBy(g => g.Running)
            .Select((item,idx) => new PieSeries<double>
            {
              Values = new List<double> { item.Sum(x => x.Elapsed) },
              Name = item.Key ? "On" : "Off",
              Stroke = null,
              Fill = new SolidColorPaint(colors[idx%2])
            });