tags:

views:

39

answers:

2

Hey,

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.

+5  A: 

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.

Jon Skeet
That looks like it would do the job, I'd have liked to have used a tuple but unfortunatly in this case I'm limited to 3.5 :(
mjmcloug
+1  A: 

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

CodingInsomnia
I like this answer as well. Never come across the let statement before.Thanks
mjmcloug