Search code examples
c#linqvaluetuple

ValueTuple in Select Linq


Good day, I have a problem, I need to pull out from query several values

var val= context.tab1.Select(x=> new {x.a,x.b,x.c});

but variable val will have anonymous type and because of that I cant complete my task. My next idea was get variables and put them into Tuple, but its not comfortable because I cant name values in Tuple in Select state

var val1= context.tab1.Select(x => Tuple.Create(x.a, x.b, x.c) );

After all of that i got a question is a way to put values from linq Select in ValueTuple? I think it must look like what

var val2= context.tab1.Select(x => (int,int,DateTime) (x.a, x.b, x.c));

Sorry for my bad English and thanks

var val= context.tab1.Select(x=> new {x.a,x.b,x.c});
var val1= context.tab1.Select(x => Tuple.Create(x.a, x.b, x.c) );
var val2= context.tab1.Select(x => (int,int,DateTime) (x.a, x.b, x.c)) ;

Solution

  • Try to add a method like this:

    static (int a, int b, DateTime c) GetValueTuple(int i1, int i2, DateTime dt) 
         => (i1, i2, dt);
    

    you can change t1...tn arbitrary.

    var val2 = context.tab1.Select(x => GetValuTuple(x.a, x.b, x.c));
    

    You can use First() to ensure that it works.

    var val3 = val2.First();