C# 通过LINQ查找目标数是否是数组中两个数的和,并获取和索引
你好,我是Linq的新手,我发现这个帖子可以解释我90%的需求 ,谢谢“pdr” 但我也需要得到索引,这是我的修改,我得到了第一个数字的索引,但我不知道如何得到第二个数字的索引C# 通过LINQ查找目标数是否是数组中两个数的和,并获取和索引,c#,linq,arrays,C#,Linq,Arrays,你好,我是Linq的新手,我发现这个帖子可以解释我90%的需求 ,谢谢“pdr” 但我也需要得到索引,这是我的修改,我得到了第一个数字的索引,但我不知道如何得到第二个数字的索引 int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var result = from item in numbers.Select((n1, idx) => new { n1,idx, shortList = n
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var result = from item in numbers.Select((n1, idx) =>
new { n1,idx, shortList = numbers.Take(idx) })
from n2 in item.shortList
where item.n1 + n2 == 7
select new { nx1 = item.n1,index1=item.idx, nx2=n2 };
这将为您提供一对项,每个项都包含数组及其索引中的一个值。这些对仅限于值之和等于目标的情况。where子句中的&&消除了重复和自匹配(适用于偶数目标)
int[]数字={1,2,3,4,5,6,7,8,9};
int目标=7;
var query=来自数字中的项1。选择((数字,索引)=>new{number=number,index=index})
从数字中的项2中选择((数字,索引)=>new{number=number,index=index})
其中item1.Number+item2.Number==target
&&项目1.索引<项目2.索引
选择新的{Item1=Item1,Item2=Item2};
foreach(查询中的var itemPair)
{
Console.WriteLine(“{0}:{1}\t{2}:{3}”,
itemPair.Item1.Index,
itemPair.Item1.Number,
itemPair.Item2.Index,
itemPair.Item2.Number);
}
如果它确实在一个数组上,那么您可以执行以下操作:
var result = from index1 in Enumerable.Range(0, numbers.Length)
from index2 in Enumerable.Range(index1 + 1,
numbers.Length - index - 1)
where numbers[index1] + numbers[index2] == targetNumber
select new { index1, index2,
value1 = numbers[index1], value2 = numbers[index2] };
否则,您可以使用包含索引两次的Select
表单:
var result = from pair1 in numbers.Select((value, index) => new { value, index})
from pair2 in numbers.Skip(pair1.index + 1)
.Select((value, index) =>
new { value, index = index - pair2.index - 1})
where pair1.value + pair2.value == targetNumber
select new { index1 = pair1.index, index2 = pair2.index,
value1 = pair1.value, value2 = pair2.value };
虽然这两个都很难看…选择许多是你需要的
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int target = 7;
var query = numbers
.SelectMany((num1,j) => numbers.Select((num2,i) => new {n1=num1, n2=num2, i=i, j=j}))
.Where(x => x.n1 + x.n2 == target && x.i < x.j);
foreach (var x in query)
Console.WriteLine(x.n1 + " and " + x.n2 + " occur at " + x.i + "," + x.j );
int[]数字={1,2,3,4,5,6,7,8,9};
int目标=7;
var查询=数字
.SelectMany((num1,j)=>number.Select((num2,i)=>new{n1=num1,n2=num2,i=i,j=j}))
其中(x=>x.n1+x.n2==target&&x.i
我发现这两个代码段都没有返回其原始数组和目标上的预期结果。第一个抛出一个索引自动失效异常
,而第二个则不返回正确的索引。两个代码段都不会返回与索引一起使用的元素值。@Anthony:Oops-将修复这两个问题。得到元素值也非常容易,这当然是O(n平方)。有一个O(n)算法来解决这个问题(如果它们被排序的话)——本质上是在矩阵上的对角行走——但是在LINQ中以纯函数的方式实现它需要相当巧妙地使用Aggregate()。感谢LINQ真的是如此强大,你对掌握它有什么建议。这听起来像是一个新问题:-)掌握它的建议。。。1.经常使用它;2.查看每个foreach循环,看看它是否更清晰/更容易用LINQ表示;3.按照StackOverflow上的LINQ标签查看人们提出的所有问题和“正确”答案。
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int target = 7;
var query = numbers
.SelectMany((num1,j) => numbers.Select((num2,i) => new {n1=num1, n2=num2, i=i, j=j}))
.Where(x => x.n1 + x.n2 == target && x.i < x.j);
foreach (var x in query)
Console.WriteLine(x.n1 + " and " + x.n2 + " occur at " + x.i + "," + x.j );