Linq选择多个列作为单独的数组

时间:2013-04-25 19:41:28

标签: c# visual-studio-2010 performance linq linq-to-sql

我有表4列。

JobId    StateId    Salary       Expense
1           1        35,000      31,000
1           1        33,000      25,000
1           2        28,000      26,000
2           2         7,000      16,000
2           2         6,000      20,000
2           1         9,000      22,000
2           1        15,000      29,000

通过在C#中使用LINQ,我想按JobId和StateId组合进行分组。对于每个组合,我想要一个Salary数组和Expense数组。

通过使用此

,我可以为每个组合获得一列作为数组
(from r in myTable.AsEnumerable()
       group r by new {
            jobId = r.Field<int>("JobId"),
            stateId = r.Field<int>("StateId")
        }).ToDictionary(
        l => Tuple.Create(l.Key.jobId, l.Key.stateId),
        l=> (from i in l select i.Field<double>("Salary")).AsEnumerable()
  );

我如何在每个组的两个数组中获得薪水和费用?

我的目标是找到每种组合的平均工资和平均费用,并进行其他操作。或者至少告诉我如何选择多个列作为单独的数组。

注意:我不想为每个组合收集匿名对象。

2 个答案:

答案 0 :(得分:4)

要在查询中选择两个不同的列作为集合,您可以执行以下操作:

var result = 
    (from r in myTable.AsEnumerable()
     group r by new 
     {
         jobId = r.Field<int>("JobId"),
         stateId = r.Field<int>("StateId")
     } into g
     select new 
     {
         g.Key,
         Salaries = g.Select(x => x.Field<double>("Salary")),
         Expenses = g.Select(x => x.Field<double>("Expense"))
     })
    .ToDictionary(
        l => Tuple.Create(l.Key.jobId, l.Key.stateId),
        l => new { l.Salaries, l.Expenses }
    );

然后你可以很容易地计算平均值:

var averageSalary = result[...].Salaries.Average();
var averageExpense = result[...].Expenses.Average();

但如果您真正需要的只是平均数,那么这将有效:

var result = 
    (from r in myTable.AsEnumerable()
     group r by new 
     {
         jobId = r.Field<int>("JobId"),
         stateId = r.Field<int>("StateId")
     } into g
     select new 
     {
         g.Key,
         AverageSalary = g.Average(x => x.Field<double>("Salary")),
         AverageExpense = g.Average(x => x.Field<double>("Expense"))
     })
    .ToDictionary(
        l => Tuple.Create(l.Key.jobId, l.Key.stateId),
        l => new { l.AverageSalary, l.AverageExpense }
    );

答案 1 :(得分:-1)

不要将LINQ用于此类声明。如果您需要计算分组和计算某种平均工资/费用,您可以尝试一个列表:

List<myType> myList = new List<myType>();

//add stuff to myList

List<myType> JobID1 = new List<myType();
List<myType> JobID2 = new List<myType();

foreach(var item in myList)
{
    if(item.JobID == 1)
        JobID1.add(item);
    if(item.JobID == 2)
        JobID2.add(item);
}

int avgSalOne;

foreach(var item in JobID1)
{
    avgSalOne += item.Salary;
}

avgSalOne = avgSaleOne / JobID2.Count;

//Note that you get Job Id 2 average salary the same way, and also the Expense by changing item. Salary to item.Expense