Lektsia_9VP
.pdfЛямбда-выражения
Если входных параметров два и более, то они разделяются запятыми и заключаются в скобки:
(x, y) => x == y
Явное указание типов:
(int x, string s) => s.Length > x
Отсутствие входных параметров задаётся пустыми скобками.
() => SomeMethod()
11
delegate bool D(); delegate bool D2(int i); class Test
{
D del; D2 del2;
public void TestMethod(int input)
{
int j = 0;
del = () => { j = 10; return j > input; };
//del2 will be invoked after TestMethod goes out of scope. del2 = (x) => { return x == j; };
//Demonstrate value of j:
//Output: j = 0
//The delegate has not been invoked yet.
Console.WriteLine("j = {0}", j); |
// Invoke the delegate. |
bool boolResult = del(); |
|
// Output: j = 10 b = True |
|
Console.WriteLine("j = {0}. b = {1}", j, boolResult);
}
12
static void Main()
{
Test test = new Test(); test.TestMethod(5);
//Prove that del2 still has a copy of
//local variable j from TestMethod. bool result = test.del2(10);
//Output: True
Console.WriteLine(result); Console.ReadKey();
}
}
13
Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)
List<string> fruits = new List<string> { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" };
IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6); foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
/*
apple mango grape
*/
14
Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>)
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
foreach (int num in squares)
{
Console.WriteLine(num);
}
/*
1
4
9
16
25
36
49
64
81
100
*/
15
SkipWhile<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)
int[] grades = { 59, 82, 70, 56, 92, 98, 85 }; IEnumerable<int> lowerGrades =
grades
.OrderByDescending(grade => grade)
.SkipWhile(grade => grade >= 80); Console.WriteLine("All grades below 80:"); foreach (int grade in lowerGrades)
{
Console.WriteLine(grade);
}
/*
70
59
56 */
16