Lambda式練習
3270 ワード
マイクロソフトのサンプルコードに基づいて、体験してみましょう.
1.
static int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
static string[] strings = new string[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
class Person {
public string Name;
public int Level;
}
static Person[] persons = new Person[] {
new Person {Name="Matt", Level=3},
new Person {Name="Luca", Level=3},
new Person {Name="Jomo", Level=5},
new Person {Name="Dinesh", Level=3},
new Person {Name="Charlie", Level=3},
new Person {Name="Mads", Level=3},
new Person {Name="Anders", Level=9}
};
2.
public static void Sample1() {
// use Where() to filter out elements matching a particular condition
IEnumerable fnums = numbers.Where(n => n s[0] == 'o');
Console.WriteLine("string starting with 'o': {0}", v);
}
4. numbers
public static void Sample3() {
// use Select() to convert each element into a new value
IEnumerable snums = numbers.Select(n => strings[n]);
Console.WriteLine("Numbers");
foreach(string s in snums) {
Console.WriteLine(s);
}
}
5. , var
public static void Sample4()
{
// use Anonymous Type constructors to construct multi-valued results on the fly
var q = strings.Select(s => new {Head = s.Substring(0,1), Tail = s.Substring(1)});
foreach(var p in q) {
Console.WriteLine("Head = {0}, Tail = {1}", p.Head, p.Tail);
}
}
6. ( )
public static void Sample5() {
// Combine Select() and Where() to make a complete query
var q = numbers.Where(n => n strings[n]);
Console.WriteLine("Numbers ++i);
// Note, the local variable 'i' is not incremented until each element is evaluated (as a side-effect).
foreach(var v in q) {
Console.WriteLine("v = {0}, i = {1}", v, i);
}
Console.WriteLine();
// Methods like ToList() cause the query to be executed immediately, caching the results
int i2 = 0;
var q2 = numbers.Select(n => ++i2).ToList();
// The local variable i2 has already been fully incremented before we iterate the results
foreach(var v in q2) {
Console.WriteLine("v = {0}, i2 = {1}", v, i2);
}
}
8.
public static void Sample7() {
// use GroupBy() to construct group partitions out of similar elements
var q = strings.GroupBy(s => s[0]); // s[0]).Select(g => new {FirstChar = g.Key, Count = g.Count()});
foreach(var v in q) {
Console.WriteLine("There are {0} string(s) starting with the letter {1}", v.Count, v.FirstChar);
}
}
10.
// use OrderBy()/OrderByDescending() to give order to your resulting sequence
var q = strings.OrderBy(s => s); // order the strings by their name
foreach(string s in q) {
Console.WriteLine(s);
}
}
11.
public static void Sample9a() {
// use ThenBy()/ThenByDescending() to provide additional ordering detail
var q = persons.OrderBy(p => p.Level).ThenBy(p => p.Name);
foreach(var p in q) {
Console.WriteLine("{0} {1}", p.Level, p.Name);
}
}
変換元:http://blog.csdn.net/kasbaster/article/details/6525085