Linq——查询语法代替循环

内容来自《c#高效编程》
看完书忍不住感叹,靠,Linq还能这样用,NB

1 循环语句

int[] foo=new int[100];
for(int num=0;num<foo.Length;num++)
    foo[num]=num*num;
foreach(int i in foo)
    console.WriteLine(i.ToString());

2 查询语句

int[] foo=(from n in Enumerable.Range(0,100)
            select n*n).ToArray();

方法(1)中的打印语句,需要为IEunmerable编写一个扩展方法

public static class Extensions{
    
    
	public static void ForAll<T>(
		this IEunmerable<T> sequence,
		Action<T> action)
	{
    
    
		foreach(T item in sequence)
			action(item);
	}
}

打印

foo.ForAll((n)=>Console.WriteLine(n.ToString());

3 应用场景
嵌套循环中使用linq查询代替,能使表达更清晰、易读。

猜你喜欢

转载自blog.csdn.net/hhhhhhenrik/article/details/105110220