C# Лямбда-вирази

2075 / C# / Лямбда-вирази

 
Як делегат, але простіше

delegate int Operation(int x, int y);

static void Main(string[] args)
{
  Operation operation = (x, y) => x + y; // створює метод в коді
  Console.WriteLine(operation(10, 20)); // 30
  Console.WriteLine(operation(40, 20)); // 60
  Console.Read();
}

// (x, y) => { Console.WriteLine("z = "); int z = x + y; return z; };

 
Спрощує написання методів

static void Show(string[] arr) => Console.WriteLine(string.Join(", ", arr));

static string Show() => "Hello Ukraine";

 
Підключає подію (+=) прямо в коді, без створення методу

private void Window_Loaded(object sender, RoutedEventArgs e)
{
  button.Click += (s, a) =>
  {
    MessageBox.Show("Work");
  };
}

// b1.MouseEnter
// b1.MouseLeave

 
Асинхронно (затримка 1с)

button.Click += async (s, a) =>
{
  await Task.Delay(1000);
  MessageBox.Show("Work");
};

 
Для 4 кнопок

Button[] b = { b1, b2, b3, b4 };
foreach (Button item in b)
{
  item.Click += (s, a) =>
  {
    MessageBox.Show("Work");
  };
}

 
Пошук в об'єктах

Pet[] pets = {
 new Pet { Name = "Андрій", Successful = true },
 new Pet { Name = "Дмитро", Successful = true },
 new Pet { Name = "Віктор", Successful = false }
};

try 
{
  int numberSuccessful = pets.Count(p => p.Successful == true);
  Console.WriteLine("There are {0} unvaccinated animals.", numberSuccessful);
}
catch (OverflowException)
{
  Console.WriteLine("Число більше за Int32");
  Console.WriteLine("Спробуйте метод LongCount()"); 
}


------------

class Pet {
  public string Name { get; set; }
  public bool Successful { get; set; }
}

 
Пошук в списку

static void Main(string[] args)
{
  IList<Student> studentList = new List<Student>() {
  new Student() { StudentID = 1, StudentName = "John", Age = 18, StandardID = 1 } ,
  new Student() { StudentID = 2, StudentName = "Steve", Age = 21, StandardID = 1 } ,
  new Student() { StudentID = 3, StudentName = "Bill", Age = 18, StandardID = 2 } ,
  new Student() { StudentID = 4, StudentName = "Ram", Age = 20, StandardID = 2 } ,
  new Student() { StudentID = 5, StudentName = "Ron", Age = 21 }
};

var studentNames = studentList.Where(s => s.Age > 18)
  .Select(s => s)
  .Where(st => st.StandardID > 0)
  .Select(s => s.StudentName);

foreach (var name in studentNames)
{
  Console.WriteLine(name);
}


------------

public class Student
{
  public int StudentID { get; set; }
  public string StudentName { get; set; }
  public int Age { get; set; }
  public int StandardID { get; set; }
}

 
Прибирання дублікатів (не дуже ефективне, в порівнянні зі звичайним циклом)

var query = from p in Process.GetProcesses()
  join mo in results.Cast<ManagementObject>() on p.Id equals (int)(uint)mo["ProcessId"]
  select new { Process = p, Path = (string)mo["ExecutablePath"] };

var uniquePaths = query.GroupBy(item => item.Path).Select(item => item.First());

 
Масив Func

Func<double, double>[] arrLiamda = { 
  x => Math.Sqrt(Math.Abs(x)),
  x => x * x * x,
  x => ++x 
};