0

Possible Duplicate:
linq case statement

please consider this scenario:

I have a function like this:

private void MyFunction(byte Period)
{
    ...

I have a table in database like this:

...    F008    F009_1    F009_2    F009_3    F009_4    F009_5    F009_6    F009_7    F009_8  ...

-------------------------------------------------------------------------------------------------

in body of function I want to do some calculation.

var MyCalculation = from r in ent.MyTable
                    group r by new { r.F000 } into grp
                    select new
                          {
                              F008 = grp.Sum(o => o.F008) 
                              F009 = ?????

the problem is in case of F009 I should do this in linq projection:

switch(Period)
{ 
    case 1:
        F009 = (Sum of F009_1) + (Sum of F009_2);
        break;
    case 2:
        F009 = (Sum of F009_3) + (Sum of F009_4);
        break;
    case 3:
        F009 = (Sum of F009_5) + (Sum of F009_6);
        break;
    case 4:
        F009 = (Sum of F009_7) + (Sum of F009_8);
        break;
}

How I can use this switch case in linq projection?

thanks

Community
  • 1
  • 1
Arian
  • 12,793
  • 66
  • 176
  • 300

2 Answers2

0

It should be like inline and join queries combination. Please tell the exact scenario or the queries you have written.

One approach you can follow is, build the query and write the switch case and include ur queries in it.. like,

case 1: var MyCalculation = from r in ent.MyTable
                    group r by new { r.F000 } into grp
                    select new
                          {
                              F008 = grp.Sum(o => o.F008) 
                              F009 =F009_1+F009_2,}

` like this similar way can be done.. anyway query will be executed once and is the easiest way

0
var groupQuery = ent.MyTable.GroupBy(r => r.F0000 );
IEnumerable<Result> query;

switch(Period)
{ 
    case 1:
        query = groupQuery.Select(grp => new Result { 
              F008 = grp.Sum(r => r.F008),
              F009 = grp.Sum(r => r.F009_1 + r.F009_2)
           };
        break;
    case 2:
        query = groupQuery.Select(grp => new Result { 
              F008 = grp.Sum(r => r.F008),
              F009 = grp.Sum(r => r.F009_3 + r.F009_4)
           };
        break;
    case 3:
        query = groupQuery.Select(grp => new Result { 
              F008 = grp.Sum(r => r.F008),
              F009 = grp.Sum(r => r.F009_5 + r.F009_6)
           };
        break;
    case 4:
        query = groupQuery.Select(grp => new Result { 
              F008 = grp.Sum(r => r.F008),
              F009 = grp.Sum(r => r.F009_7 + r.F009_8)
           };
        break;
}

var MyCalculation = query.ToList();

And your DTO:

public class Result
{
    // provide actual data types
     public int F008 { get; set; }
     public int F009 { get; set; }
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459