Reputation: 67
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
Upvotes: 4
Views: 175
Reputation: 828
You can either implement the IComparable
interface to the class you are querying or create a new class that implements the IComparer
interface and pass it as parameter to the sort method.
Upvotes: 1
Reputation: 120420
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.
Upvotes: 6
Reputation: 6525
For the general problem I'd use the Schwartzian transform, a common schema used in Perl. It should be easy to port the underlying method to .net
Your case is even simpler as you have full control of the data access:
var tuples = from dc in GetDashboardData
group dc by dc.serviceType into g
select new{
Cost = g.Sum(sc=>sc.serviceCost),
Type = g.Key,
};
var sorted = tuples.OrderByDescending(t=>t.Cost).Select(t=>t.Type);
return sorted.ToList();
Upvotes: 3