0

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))

2 Answers2

2

Based on your code samples referencing context I assume you are talking about some ORM like Entity Framework which uses not just "simple" LINQ-to-Objects but performs SQL generation based on combination of IQueryable interface which uses expression trees.

If yes - then no, currently it is not possible to create value tuples via "standard" syntax because it is not possible to use value tuples literals in the expression trees. You can monitor following issues/discussions at the github:

If you really want to you can transform your IQueryable to IEnumerable and the select to a value tuple:

var result = (await _context.tab1
   .Select(x => new {x.a, x.b})
   .ToListAsync())
   .Select(ac => (ac.a, ac.a))
   .ToList();

Or

var result = _context.tab1
   .Select(x => new {x.a, x.b})
   .AsEnumerable()
   .Select(ac => (ac.a, ac.a))
   .ToList();

Or via method indirection as @iman safari suggests.

But I would argue that in any case is a bit pointless, because creating a new type with records is very easy with modern .NET. So just create a type and use it.

Read also:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
1

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();
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
iman safari
  • 194
  • 1
  • 1
  • 8