Iva*_*ers 3 c# linq lambda expression
我有一个RekenReeks类,它返回从2开始的数字,乘以2.所以{2,4,8,16,32,64}
现在我了解了TakeWhile和SkipWhile方法以及LINQ.
所以我创建了3个变量,它们应该存储完全相同,但我Console.WriteLine唯一的打印选择1而不是2和3.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
RekenReeks reeks = new RekenReeks(2, n => n * 2);
var selection = from i in reeks
where i > 10
&& i < 1000
select i;
var selection2 = reeks.TakeWhile(n => n < 1000 && n > 10);
var selection3 = reeks.SkipWhile(n => n > 1000 && n < 10);
foreach (int i in selection)
{
Console.WriteLine("selection1 {0}",i);
}
foreach (int i in selection2)
{
Console.WriteLine("selection2 {0}", i);
}
foreach (int i in selection3)
{
Console.WriteLine("selection3 {0}", i);
}
Console.ReadLine();
}
}
public class RekenReeks : IEnumerable<int>
{
Func<int, int> getNew;
int number;
public RekenReeks(int starton, Func<int, int> getNewThing)
{
getNew = getNewThing;
number = starton;
}
public IEnumerator<int> GetEnumerator()
{
yield return number;
for (; ; )
{
yield return getNew(number);
number = getNew(number);
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
Run Code Online (Sandbox Code Playgroud)
你的序列是无限的(理论上).你假设太多了.程序的功能不可能知道您的序列严格单调增加.
var selection = from i in reeks
where i > 10
&& i < 1000
select i;
Run Code Online (Sandbox Code Playgroud)
这永远不会停止.因为where总是会拉的下一个值,它不知道它的条件将得到满足,它总是有来检查下一个值.
var selection2 = reeks.TakeWhile(n => n < 1000 && n > 10);
Run Code Online (Sandbox Code Playgroud)
这将取值,而它们在11到999之间.当序列以2开头时,它将在第一个值上停止.
var selection3 = reeks.SkipWhile(n => n > 1000 && n < 10);
Run Code Online (Sandbox Code Playgroud)
这将在11到999之间跳过值.由于第一个是2,它将跳过无,因此产生全部.
| 归档时间: |
|
| 查看次数: |
890 次 |
| 最近记录: |