2013-07-11 26 views
4

我需要创建一个表示总和值前五个的字符串列表。C#按双精度列表对字符串列表进行排序

我有数百个票据属于不同的服务

前的数据库。电动$ 600 2013年1月 水$ 50 2013年1月

我需要总结所有这些我在这里做

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

    } 

我创建的字符串列表通过下面的代码下面

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"); 
     } 
    } 
相同的服务

现在这两个列表中的数据是并行的意思 GetSumOfSingleServices [0]是GetServiceNames [0]的值,依此类推。

我想要一个列表,其中字符串按照GetSumOfSingleServices的最高值排列,等等。因此,如果最高的GetSumOfSingleServices [3]及其并行字符串是GetServiceNames [3],那么我希望GetServiceNames [3]成为我在列表中的第一个条目。

不知道如何通过double值对字符串列表进行排序。

+4

为什么不用一个包含名称和总和的复合对象创建单个列表?这将是超级简单的。同步指数的气味真的很差。 – spender

回答

3

对于一般的问题,我会用Schwartzian transform,在Perl中使用的通用架构。它应该很容易port the underlying method to .net

你的情况是,即使简单,因为你拥有的数据访问完全控制:

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(); 
6

,看起来像这样的源泉,所有的转换变得轻松:

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

(您可能会考虑制作具有两个属性namesum的具体类,而不是上面的匿名对象声明)。

现在:

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

等。

同步列表吸。

+1

完全同意同步列表是一场噩梦。如果数据在GetSumOfSingleServices()和GetServiceNames()之间改变,或者数据按照您预期的顺序返回,那么一切都结束了。这是以一致且可预测的方式获得所需信息的完美方式。 – MadHenchbot

1

您可以实现IComparable接口到您正在查询的类,也可以创建一个实现了接口的新类,并将其作为参数传递给排序方法。

相关问题