使用linq查询简化流程

时间:2015-09-04 11:24:32

标签: c# asp.net-mvc performance linq

这是我的表:

PupilNutrition

Id     PupilId   NutritionId
1       10          100  
2       10          101

我的另一张表营养

Id  Nutritioncategory  BatchId   NutritionRate   NutritionId   Operation
1       A                1         9000             100          1
2       B                1         5000             100          0
3       C                1         5000             100          1
4       D                2         6000             101          2           
5       E                2         7000             101          2         
6       F                2         8000             101          0          

这是存储最终费率的一个字段:

decimal Rate= 0;

案例1 值为0且批次为1的操作字段

 Rate= Rate + NutritionRate(i.e 5000 because for batch id 1 with condition 0 only 1 record is there).

案例2 现在为值为1且批次为1的操作字段

Here i want to sum up both the value i.e(10000 and 5000) but during addition if sum of both is greater than 10000 then just take 10000 else take sum like this:
if(9000 + 5000 > 10000)
  Rate= 10000
else
    Rate=Rate + (Addition of both if less than 10000).

案例3 现在为值0和批次ID为2的操作字段

 Rate= Rate + NutritionRate(i.e 8000 because for batch id 1 with condition 0 only 1 record is there).

案例4 现在为值为2且批次为ID 2的操作字段

Here I will select Maximum value from Nutrition Rate field if there are 2 records:
Rate=Rate - (Maximum value from 6000 and 7000 so will take 7000).

我的班级档案:

 public partial class PupilNutrition
    {
        public int Id { get; set; }
        public int PupilId { get; set; }
        public int NutritionId { get; set; }
    }

 public partial class Nutrition
    {
        public int Id { get; set; }
        public string Nutritioncategory { get; set; }
        public decimal NutritionRate  { get; set; }
        public Nullable<int> NutritionId { get; set; }
    }

这就是我完成的方式:

batchId=1 or 2;//
 List<int> NutritionId = db.PupilNutrition.Where(x => PupilId  == 10).Select(c => c.NutritionId).ToList();  //output 100,101
 var data = db.Nutrition.Where(x => x.BatchId == batchId && NutritionId.Contains(x.NutritionId.Value)).ToList();

我试过这样但是它是一个劳动过程:

var data1=data.where(t=>t.Operation==0);
Rate= Rate + data1.Sum(p => p.NutritionRate);

类似于操作1:

var data2=data.where(t=>t.Operation==1);
This is left because here i need to sum up 2 value if two records are there as shown in my above cases and if sum is greater than 10000 than select 10000 else select sum.

类似于行动2:

var data3=data.where(t=>t.Operation==2);
Rate= Rate - data3.Max(p => p.NutritionRate);

我认为我已经完成了一个劳动过程,因为我可以通过linq查询以更好的方式完成这个过程。

那么有人可以帮我简化linq查询中的整个过程,甚至是更好的方法,并为剩下的Operation Value 2提供解决方案吗?

4 个答案:

答案 0 :(得分:11)

最短并不总是最好的。

就个人而言,我认为单个复杂的LINQ语句可能难以阅读且难以调试。

以下是我要做的事情:

    public decimal CalculateRate(int pupilId, int batchId)
    {
        return db.Nutrition
            .Where(x => x.BatchId == batchId && db.PupilNutrition.Any(y => y.PupilId == pupilId && y.NutritionId == x.NutritionId))
            .GroupBy(x => x.Operation)
            .Select(CalculateRateForOperationGroup)
            .Sum();
    }

    public decimal CalculateRateForOperationGroup(IGrouping<int, Nutrition> group)
    {
        switch (group.Key)
        {
            case 0:
                // Rate = Sum(x)
                return group.Sum(x => x.NutritionRate);
            case 1:
                // Rate = Min(10000, Sum(x))
                return Math.Min(10000, group.Sum(x => x.NutritionRate));
            case 2:
                // Rate = -Max(x)
                return -group.Max(x => x.NutritionRate);
            default:
                throw new ArgumentException("operation");
        }
    }

然后您可以按如下方式使用它:

var rateForFirstBatch = CalculateRate(10, 1);
var rateForSecondBatch = CalculateRate(10, 2);

答案 1 :(得分:5)

通过以下群组更容易:

int sumMax = 10000;
var group = from n in nutrition
    group n by new { n.Operation, n.BatchId } into g
    select new { BatchId = g.Key.BatchId, 
        Operation = g.Key.Operation, 
        RateSum = g.ToList().Sum(nn => nn.NutritionRate), 
        RateSumMax = g.ToList().Sum(nn => nn.NutritionRate) > sumMax ? sumMax : g.ToList().Sum(nn => nn.NutritionRate), 
        RateMax = g.ToList().Max(nn => nn.NutritionRate) };
var result = from g in group
    select new {
        BatchId = g.BatchId,
        Operation = g.Operation,
        Rate = g.Operation == 1 ? g.RateSumMax :
               g.Operation == 2 ? g.RateMax :
               g.RateSum //default is operation 0
    };
var totalRate = result.Sum(g=>g.Rate);

答案 2 :(得分:4)

<强>更新 此查询看起来应该为您完成工作。请注意,我还没有对其进行测试,因此可能会出现一两个语法错误,但这个想法看似合理。

var rate = db.Nutrition
        .GroupBy(n => new { n.BatchId, n.Operation })
        .Select(g => g.Sum(n => n.NutritionRate) > 10000 ? 10000 : g.Sum(n => n.NutritionRate))
        .Sum();

或者,如果您想要查询每个案例&#39;:

rate = db.Nutrition
            .Where(n => n.BatchId == 1 && n.Operation == 0)
            .Sum(n => n.NutritionRate); //Case 1

rate += Math.Min(
            10000,  //Either return 10,000, or the calculation if it's less than 10,000
            db.Nutrition
            .Where(n => n.BatchId == 1 && 
                        n.Operation == 1) //filter based on batch and operation
            .Sum(n => n.NutritionRate) //take the sum of the nutrition rates for that filter
        ); //Case 2

rate += db.Nutrition
            .Where(n => n.BatchId == 2 && n.Operation == 0)
            .Sum(n => n.NutritionRate); //Case 3

rate += Math.Min(
            10000,  //Either return 10,000, or the calculation if it's less than 10,000
            db.Nutrition
            .Where(n => n.BatchId == 2 && 
                        n.Operation == 2) //filter based on batch and operation
            .Sum(n => n.NutritionRate) //take the sum of the nutrition rates for that filter
        ); //Case 4

答案 3 :(得分:4)

试试这个。我打破了查询以使其清楚,但您只能在一个语句中将其组合在一起。

        //// Join the collection to get the BatchId
        var query = nutritionColl.Join(pupilNutrition, n => n.NutritionId, p => p.NutritionId, (n, p) => new { BatchId = p.Id, Nutrition = n });

        //// Group by BatchId, Operation
        var query1 = query.GroupBy(i => new { i.BatchId, i.Nutrition.Operation });


        //// Execute Used cases by BatchId, Operation
        var query2 = query1.Select(grp =>
                {
                    decimal rate = decimal.MinValue;
                    if (grp.Count() == 1)
                    {
                        rate = grp.First().Nutrition.NutritionRate;
                    }
                    else if (grp.First().BatchId == 1)
                    {
                        var sum = grp.Sum(i => i.Nutrition.NutritionRate);
                        rate = sum > 10000 ? 10000 : sum;
                    }
                    else
                    {
                        rate = grp.Max(i => i.Nutrition.NutritionRate);
                    }

                    return new { BatchId = grp.First().BatchId, Operation = grp.First().Nutrition.Operation, Rate = rate };
                }
        );

        //// try out put
        foreach (var item in query2)
        {
            Console.WriteLine("{0}  {1} {2} ", item.Operation, item.BatchId, item.Rate);
        }

希望有所帮助