Home > Mobile >  Change value that is outside of query in Linq select
Change value that is outside of query in Linq select

Time:05-08

This is a bit outside of data topic, but I have been having hard times to figure out how it can be done. I have a chart control that is using colours for each chart section. I would like to specify constant colours for my chart so that they would be not generated randomly.

Here is my linq query:

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

Now my colour is always Yellow = SKColors.Yellow. How I can make an array of colours. For example SKColors.Yellow, SKColors.Blue and then use them inside my Select to pass them for each section?

Here is an array example:

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

So question is how to pass 0 and then 1 in colors[0]?

CodePudding user response:

We can try to use Select overload method which can pass the index number from our iteration currently

A transform function to apply to each source element; the second parameter of the function represents the index of the source element.

Then we can try to use mod (%) by the index number to make sure one is Yellow, another is 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])
        });
  • Related