Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

out variables in a linq statement

Tags:

c#

linq

I can fix this problem by messing with outher parts of my codebase but I thought I'd ask to see if there is an easier way of doing this.

I've got the following linq query.

(select a in objectA
where a.type = 1
select new 
{
    Id = a.Id,
    Field2 = <needThisValue>
    Field3 = <needThisValue>
}).ToList();

Now the two "needThisValues" need to be supplied via out variables of a method that accepts a, such as

TestMethod(object a, out string stringA, out string StringB)

So is there anyway I can cleverly call this method from within the linq statement to populate the two fields?

Thanks in advance.

like image 377
mat-mcloughlin Avatar asked Feb 26 '23 11:02

mat-mcloughlin


1 Answers

I don't think you can do this within a query expression, but you can do it with block lambda statements:

var query = objectA.Where(a => a.type == 1)
                   .Select(a => {
                               string Field2;
                               string Field3;
                               TestMethod(a, out Field2, out Field3);
                               return new {
                                   a.Id, Field2, Field3
                               };
                           });
                   .ToList();

I think I'd personally prefer to use a method returning a tuple, and then work with that instead, but the above should work.

like image 127
Jon Skeet Avatar answered Mar 07 '23 14:03

Jon Skeet