简体   繁体   中英

C# Linq - Refactoring ForEach Loop with Sub List

Am trying to refactor some data in order to display some charts.

I can't seem to figure out why using the following, it lists all the values at the top rather than being sequential like the source data.

var categories = VehicleSales.Select(v => v.name).Distinct().ToList();
        var refactoredResults = new List<StackedColumnChart>();

        foreach (var category in categories)
        {
            var subresult = VehicleSales.Where(x => x.vehicleType == category)
                .GroupBy(x => x.vehicleType)
                .Select(gcs => new StackedColumnChart
                {
                    Category = category,
                    Values = gcs.Select(x => (int)x.data).DefaultIfEmpty(0).ToList()
                }).ToList();
            refactoredResults.AddRange(subresult);
        }

Source Data:

在此处输入图像描述

Then the actual results and expected results:

在此处输入图像描述

Thanks in advance!

You can do that without loop and selecting a distinct values, just use GroupBy method and map each group to StackedColumnChart using Select

var refactoredResults = VehicleSales
    .GroupBy(s => s.Category)
    .Select(g => new StackedColumnChart
    {
        Category = g.Key,
        Values = g.Select(s => s.Value).ToList()
    })
    .ToList();

If the original data is not sorted and you'll need to sort the values by week number, you can use OrderBy clause before selecting a values Values = g.OrderBy(s => s.WeekNumber).Select(s => s.Value).ToList()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM