views:

37

answers:

3

Hi All

I have a list of objects, which has a method that has a couple of out parameters. How do i call this method on each object, get the out parameter values and use them later on in the query, perhaps for checking in a where clause?

Is this possible and if so can someone please demonostrate through sample code.

Thanks!

+1  A: 

Maybe you should use a for each loop and then use your query?

(Actually, it's hard to say what to do best in this situation without knowing your code)

dkson
For my specific scenario, the cleanest and most sensible way to do this would be a combination of a loop and linq. I think i've been trying to overuse Linq.
c0D3l0g1
Yeah, happens to me too from time to time. Keep it simple! :)
dkson
+1  A: 

Here is one way of accessing the values of out parameters in your LINQ query. I dont think that you can use the out-values from say a where in a later select: list.Where(...).Select(...)

List<MyClass> list; // Initialize

Func<MyClass, bool> fun = f =>
{
    int a, b;
    f.MyMethod(out a, out b);
    return a == b;
};
list.Where(fun);

Where MyClass is implemented something like this;

public class MyClass
{
    public void MyMethod(out int a, out int b)
    {
        // Implementation
    }
}
Martin Ingvar Kofoed Jensen
+1  A: 

This uses Tuple<T1,T2> from .NET 4.0, but can be adapted for earlier versions:

//e.g., your method with out parameters
void YourMethod<T1,T2,T3>(T1 input, out T2 x, out T3 y) { /* assigns x & y */ }

//helper method for dealing with out params
Tuple<T2,T3> GetTupleOfTwoOutValues<T1,T2,T3>(T1 input)
{ 
   T2 a;
   T3 b;
   YourMethod(input, out a, out b);
   return Tuple.Create(a,b);
}

IEnumerable<Tuple<T2,T3>> LinqQuery<T1,T2,T3>(IEnumerable<T1> src, T2 comparisonObject)  
{
   return src.Select(GetTupleOfTwoOutValues)
             .Where(tuple => tuple.Item1 == comparisonObject);
}
Mark Cidade