使用linq避免嵌套循环

use*_*102 5 c# linq

我想创建一个方法来查找两个数之和的索引target.

所以,我创建了这个方法:

public static int[] TwoSum(int[] nums, int target)
{
    for (var i = 0; i < nums.Length; i++)
    {
        for (var j = 0; j < nums.Length; j++)
        {
            if (j == i) continue;

            if (nums[i] + nums[j] == target)
            {
                return new[] { i, j };
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个工作正常.但是,我正在努力学习一些LINQ并且无法弄明白.我查看了各种示例,但我总是卡住,因为我使用了两次相同的数组.所以我不知道要选择什么以及如何访问它两次,同时确保它不会两次通过相同的索引.

任何从上述循环获得LINQ的帮助将不胜感激.

样本数据:

var nums = new [] { 2, 7, 11, 15 };
var target = 9;
Run Code Online (Sandbox Code Playgroud)