开发者

out variables in a linq statement

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.


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.


You could probably create a private method that returns a Tuple and use it.

Something along the lines of:

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

   TestMethod(a, out stringA, out stringB);

   return Tuple.Create(stringA, stringB);
}

Then you can use it in a let statement like this:

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

Didn't compile this so there could be errors in there..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜