通过LINQ查找目标数字是否是数组中两个数字的总和,并获取和指数

时间:2010-04-10 03:40:14

标签: c# linq arrays

您好我是Linq的新手,我发现这个帖子解释了我需要的90% https://stackoverflow.com/questions/2331882?tab=newest#tab-top,谢谢“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 = numbers.Take(idx) })
                     from n2 in item.shortList
                     where item.n1 + n2 == 7
                     select new { nx1 = item.n1,index1=item.idx, nx2=n2  };

3 个答案:

答案 0 :(得分:3)

SelectMany就是您所需要的......

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

答案 1 :(得分:1)

这将为您提供一对项目,每个项目都包含数组及其索引中的值。这些对被限制在值的总和等于目标的位置。和&amp;&amp;在where子句中消除了重复和自我匹配(适用于偶数目标)。

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

int target = 7;

var query = from item1 in numbers.Select((number, index) => new { Number = number, Index = index })
            from item2 in numbers.Select((number, index) => new { Number = number, Index = index })
            where item1.Number + item2.Number == target
            && item1.Index < item2.Index
            select new { Item1 = item1, Item2 = item2 };

foreach (var itemPair in query)
{
    Console.WriteLine("{0}:{1}\t{2}:{3}",
        itemPair.Item1.Index,
        itemPair.Item1.Number,
        itemPair.Item2.Index,
        itemPair.Item2.Number);
}

答案 2 :(得分:0)

如果它肯定在数组上,那么你可以这样做:

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

这两件事真的很难看......