简体   繁体   English

.NET LINQ 在查询和使用 Out 值中带有 Out 参数的调用方法

[英].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?我如何在每个 object 上调用此方法,获取输出参数值并稍后在查询中使用它们,也许是为了检查 where 子句?

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? 也许您应该为每个循环使用a,然后再使用查询?

(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. 这是在LINQ查询中访问out参数值的一种方法。 I dont think that you can use the out-values from say a where in a later select: list.Where(...).Select(...) 我不认为您可以在以后的select中使用where中的出值: 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; 在实现MyClass的地方,像这样;

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: 这使用.NET 4.0中的Tuple<T1,T2> ,但可以适用于早期版本:

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

You could use anonymous objects and the let keyword:您可以使用匿名对象和let关键字:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM