Out in linq expression

I can solve this problem by messing around with the external parts of my code base, but I thought I'd ask to see if there was an easier way to do this.

I have the following linq request.

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

Now two "needThisValues" should be provided through the external variables of a method that takes a, for example

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

So, anyway, can I artfully call this method from a linq statement to populate two fields?

Thanks in advance.

+3
source share
2 answers

I don’t think you can do this in a query expression, but you can do it with blocks of lambda operators:

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

, , , , .

+5

, , .

- :

private Tuple<string,string> TestMethodInternal(object a)
{
   string stringA;
   string stringB;

   TestMethod(a, out stringA, out stringB);

   return Tuple.Create(stringA, stringB);
}

let :

...
where a.type = 1
let t = TestMethodInternal(a)
select new 
{
    Id = a.Id,
    Field2 = t.Item1,
    Field3 = t.Item2,
}

, .

+1

Source: https://habr.com/ru/post/1759512/


All Articles