Search code examples
c#wpflivecharts

Build PieChart in LiveCharts2 from Linq query


I am trying to get PieCharts visible in my WPF application. There is an example available and it seems to be working fine. However I am trying to do the same from linq query and can't understand how to solve that equation.

Here is an example:

Xaml part:

<lvc:PieChart x:Name="PieChart" LegendPosition="Right" Series="{Binding OnLoaded}" InitialRotation="-90"></lvc:PieChart>

and C# code:

private async void OnLoaded()
        {
                IEnumerable<double> a = new List<double> { 1 };
                IEnumerable<double> b = new List<double> { 0 };
                IEnumerable<double> c = new List<double> { 0 };

                IEnumerable<ISeries> Series = new List<ISeries>
                {
                    new PieSeries<double> { Values = a, Name = "a" },
                    new PieSeries<double> { Values = b, Name = "b" },
                    new PieSeries<double> { Values = c, Name = "c"  }
                };
                LivePieChart3.Series = Series;
            }
        }

Then I am trying to do the same from linq, but I think this is completely wrong?:

private void InitializePieChart()
{
  List<ISeries> projectNumbers = this.Projects.Select(x => new List<ISeries>
  {
   new PieSeries<double> 
   {
    Values = x.Revenue,
    Name = x.ProjectName,
   }
  });

  this.Series = new ObservableCollection<ISeries>(projectNumbers);
}

How to create a new new PieSeries<double> after new List<ISeries>?

Here is my model:

  public class ProjectModel
  {
    public Guid Id { get; set; }
    public string ProjectName { get; set; }
    public string ProjectNumber { get; set; }
    public double Revenue { get; set; }
    public DateTime CreationDate { get; set; }

    public virtual ICollection<TaskModel> Tasks { get; set; }
  }

Projects in ViewModel:

private ObservableCollection<ProjectModel> projects;
public ObservableCollection<ProjectModel> Projects
{
  get => this.projects;
  set
  {
    this.projects = value;
    this.OnPropertyChanged();
  }
}

Here is LiveCharts2 project: https://github.com/beto-rodriguez/LiveCharts2


EDIT:

With Ash's suggestion in comments I receive following:

enter image description here


Solution

  • private void InitializePieChart()
    {
        IEnumerable<ISeries> projectNumbers = this.Projects.Select(x => 
        new PieSeries<double> 
        {
            Values = new List<double> { x.Revenue },
            Name = x.ProjectName,
        });
    
        this.Series = new ObservableCollection<ISeries>(projectNumbers);
    }