尽管有不同的数据源,LINQ查询返回相同的结果

时间:2013-12-01 08:24:41

标签: c# linq

我正在尝试以下方法:

int[] numbers = { 12, 14, -12, -8, 0, 17 };

    var pos =    from number in numbers
                    where number > 0
                    select number;

    Console.WriteLine  ( "- - - All numbers - - - " );
    foreach (var number in numbers)
        Console.Write ( "{0} " , number );

    Console.WriteLine();
    Console.WriteLine ( "- - - Positive numbers ( First ) - - -" );
    foreach ( var number in pos )
        Console.Write("{0} ", number);

    Console.WriteLine();
    numbers = new int[]{ 12, 14, -12, -8, 0, 17, 11, 10, -30, -15 };
    Console.WriteLine("- - - All numbers - - - ");
    foreach (var number in numbers)
        Console.Write("{0} ", number);

    Console.WriteLine();
    Console.WriteLine("- - - Positive numbers ( Second ) - - -");
    foreach (var number in pos)
        Console.Write("{0} ", number);

尽管我更改了数组中的元素,但我获得了以下结果:

- - - All numbers - - -
12 14 -12 -8 0 17
- - - Positive numbers ( First ) - - -
12 14 17
- - - All numbers - - -
12 14 -12 -8 0 17 11 10 -30 -15
- - - Positive numbers ( Second ) - - -
12 14 17

2 个答案:

答案 0 :(得分:4)

您在第二个pos中循环显示foreach。它记得从最少运行的结果。如果要获得新结果,则必须在打印结果之前再次查询numbers。只是做

Console.WriteLine();
numbers = new int[]{ 12, 14, -12, -8, 0, 17, 11, 10, -30, -15 };
Console.WriteLine("- - - All numbers - - - ");
foreach (var number in numbers)
    Console.Write("{0} ", number);

pos = from number in numbers
      where number > 0
      select number;

Console.WriteLine();
Console.WriteLine("- - - Positive numbers ( Second ) - - -");
foreach (var number in pos)
    Console.Write("{0} ", number);

但我建议改用以下内容。

foreach (var number in numbers.Where(n => n > 0))
    Console.Write("{0} ", number);

修改

这是一种方法。

Func<int, bool> comparer = n => n > 0;
foreach (var number in Compare(numbers, comparer))
            System.Console.Write("{0} ", number);

Compare方法正在

public IEnumerable<int> Compare(IEnumerable<int> source, Func<int, bool> comparer)
{
    return source.Where(comparer);
}

您也可以编写扩展方法。这么多可能的方式取决于你想去的方向。

答案 1 :(得分:2)

实际上你第二次没有重新生成 pos 。因此,您第二次显示的 pos 实际上是第一次 pos 生成。

将代码的第二部分更改为:

Console.WriteLine();
numbers = new int[]{ 12, 14, -12, -8, 0, 17, 11, 10, -30, -15 };
Console.WriteLine("- - - All numbers - - - ");
foreach (var number in numbers)
    Console.Write("{0} ", number);

pos =    from number in numbers
                where number > 0
                select number;

Console.WriteLine();
Console.WriteLine("- - - Positive numbers ( Second ) - - -");
foreach (var number in pos)
    Console.Write("{0} ", number);

它应该可以解决你的问题。虽然这不是一个好习惯。

编辑:对不起,我没注意到你已经接受了答案。