我有一个返回简单int[2]
的方法。数组的两个元素都需要分别分配给int r
和int c
局部变量。我想在一个Linq查询中实现所有这些。有什么办法吗?
这是我想要实现的伪代码,但显然不起作用。我对Linq不太了解,我正在努力做得更好。 Method(r,c)
是返回int[2]
的方法。我想拉出每个元素并分配int[0] = r
和int[1] = c
。
void Foo(int r, int c)
{
Method(r,c).Select(([0],[1]) => { r = [0]; c = [1]; });
}
int[] Method(int r, int c)
{
///stuff///
}
答案 0 :(得分:2)
static class
来制作Select
方法Func<int[],T>
并重新运行T(T为泛型)public class Program
{
public static void Main()
{
var result = Method(1, 2).Select( (r,c) => new { r,c });
Console.WriteLine(result);
}
static int[] Method(int r,int c) => new[] {r,c};
}
public static class LinqExtension
{
public static T Select<T>(this int[] ints, Func<int,int, T> func) => func(ints[0],ints[1]);
}
或者您可以将Method与params int[]
public class Program
{
public static void Main()
{
var value = Method(1, 2).Select((int[] arr) => new{r = arr[0],c = arr[1]});
Console.WriteLine(value); //result : { r = 1, c = 2 }
}
public static int[] Method(params int[] ints)
{
return ints;
}
}
public static class LinqExtension
{
public static T Select<T>(this int[] ints,Func<int[],T> func){
return func(ints);
}
}
在这种情况下,我将如何使用out关键字?假设我正在使用从Foo()值传递的参数。
您可以使用out
关键字:
public class Program
{
public static void Main()
{
Method(1, 2).Select( out int r ,out int c);
Console.WriteLine(r);
Console.WriteLine(c);
}
static int[] Method(int r,int c) => new[] {r,c};
}
public static class LinqExtension
{
public static void Select(this int[] ints, out int r, out int c)
{
r = ints[0];
c = ints[1];
}
}