Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# sorting a List of Strings by a List of Doubles

Tags:

c#

linq

I need to create a list of strings that represent the top five of the summed values.

I have a database with hundreds of bills pertaining to different services

ex. electric $600 January 2013 Water $50 January 2013

I need to sum all the same services which I have done here

public List<Double> GetSumOfSingleServices
    {
        get
        {

            var sums = (from dc in GetDashboardData                            
                        group dc by dc.serviceType into g
                        select g.Sum(sc => sc.serviceCost)).ToList();

            return sums;
        }
        set
        {
            NotifyPropertyChanged("GetSumOfSingleServices");
        }

    }

I created a list of string by the following code below

public List<String> GetServiceNames
    {
        get
        {

            var names = (from dc in GetDashboardData
                         group dc by dc.serviceType into g                             
                         select g.First().serviceType).ToList();

            return names;
        }
        set
        {
            NotifyPropertyChanged("GetServiceNames");
        }
    }

Now the data in these two lists are parallel meaning GetSumOfSingleServices[0] is the value for GetServiceNames[0] and so on.

I would like have a list that has the Strings ranked by the highest value from GetSumOfSingleServices first and so on.

So if the highest GetSumOfSingleServices[3] and its parallel string is GetServiceNames[3], then I would like GetServiceNames[3] to be my first entry in the list.

Not sure how to sort through the list of strings by the double values.

That

like image 977
GodfatherSaint Avatar asked Dec 27 '22 00:12

GodfatherSaint


1 Answers

With a source that looks like this, all your transformations become easy:

var compositeList = GetDashboardData
     .GroupBy(dc => dc.serviceType)
     .Select(g => new{
                    name = g.Key, 
                    sum = g.Sum(sc => sc.serviceCost)})
     .ToList();

(you might consider making a concrete class with two properties name and sum instead of the anonymous object declaration above).

Now:

compositeList.OrderByDescending(x => x.sum).Select(x => x.name);

and so on.

Synchronized lists suck.

like image 128
spender Avatar answered Jan 12 '23 12:01

spender