c0D3l0g1c
c0D3l0g1c

Reputation: 3164

.NET LINQ Call Method with Out Parameters Within Query and use Out Values

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!

Upvotes: 2

Views: 4070

Answers (5)

Formentz
Formentz

Reputation: 1195

You could use anonymous objects and the let keyword:

var texts = new[] { "dog", "2", "3", "cat" };
var checks = from item in texts
             let check = new
             {
                 Word = item,
                 IsNumber = int.TryParse(item, out var n),
                 Value = n,
             }
             where check.IsNumber
             select check;
foreach(var item in checks) 
{
    Console.WriteLine($"'{item.Word}' is the number {item.Value}");
}

Upvotes: 1

Gustavo Bezerra
Gustavo Bezerra

Reputation: 11044

You can use tuples (without any helper methods):

var text = "123,456,abc";
var items = text.Split(',')
    .Select(x => (long.TryParse(x, out var v), v))
    .Where(x => x.Item1)
    .Select(x => x.Item2);

foreach (var item in items)
{
    Console.WriteLine(item);
}

Output

123
456

This article has some additional solutions: https://mydevtricks.com/linq-gems-out-parameters

Upvotes: 0

Mark Cidade
Mark Cidade

Reputation: 100007

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

Upvotes: 1

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

Upvotes: 2

sloth
sloth

Reputation: 101122

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)

Upvotes: 1

Related Questions