.NET LINQ Call Method with Out Parameters Within Query and use Out Values
I have a list of开发者_StackOverflow社区 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!
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)
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
}
}
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);
}
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
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}");
}
精彩评论