Linq-query syntax instead of loops

The content comes from "c# Efficient Programming"
after reading the book, I can't help but sigh, damn, Linq can still be used like this, NB

1 Loop statement

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 Query statement

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

The print statement in method (1) needs to write an extension method for IEunmerable

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

print

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

3 Application scenarios
Using linq query instead of nested loop can make the expression clearer and easier to read.

Guess you like

Origin blog.csdn.net/hhhhhhenrik/article/details/105110220