c# - Syntax to execute code block inside Linq query? -


here's code (obviously) doesn't compile:

var q = x in myanonymoustypecollection         select new {           x.id,           calcfield = {                          switch(x.somefield) {                           case 1:                             return math.sqrt(x.field1);                           case 2:                             return math.pow(x.field2, 2);                           default:                             return x.field3;                         }                       }         }; 

you picture; i'm trying calculate calcfield in different way, depending on value of somefield is. can't use func<> (or can i?), because input type anonymous. what's right syntax work?

first off, prefer method chain syntax on query syntax linq. can easily.

var q = myanonymoustypecollection     .select(x =>              {                 object calcfield;                    switch(x.somefield)                   {                       case 1:                         calcfield = math.sqrt(x.field1);                       case 2:                         calcfield =  math.pow(x.field2, 2);                       default:                         calcfield = x.field3;                   return new                          {                             x.id,                             calcfield = calcfield                         };             }); 

without using method chains, need either method or func. let's assume func

//replace these actual types if can. func<dynamic, dynamic> calculatefield =      x =>      {         switch(x.somefield) {             case 1:                 return math.sqrt(x.field1);             case 2:                 return math.pow(x.field2, 2);             default:                 return x.field3;     }  var q = x in myanonymoustypecollection         select new { x.id, calcfield = calculatefield(x) }; 

note: didn't write in ide, please excuse simple errors.

here msdn dynamic. however, have found once need start passing anonymous types around, best make actual class.


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -