πŸ–₯ Lists & enumerables



ΠŸΡ€ΠΎΠ΄ΠΎΠ»ΠΆΠ°Π΅ΠΌ Π³ΠΎΠ²ΠΎΡ€ΠΈΡ‚ΡŒ ΠΎ Linq. Π‘ΠΈΠ±Π»ΠΈΠΎΡ‚Π΅ΠΊΠ° Linq ΠΎΡ‡Π΅Π½ΡŒ ΠΏΠΎΠ»Π΅Π·Π½Π° для написания быстрых, однострочных Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΉ, ΠΏΡ€ΠΈΠ²Π΅Π΄Π΅ΠΌ нСсколько ΠΏΡ€ΠΈΠΌΠ΅Ρ€ΠΎΠ² с ΠΊΠΎΠ΄ΠΎΠΌ:



β–ͺΠ‘ΡƒΠΌΠΌΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ всСх чисСл Π² Π΄ΠΈΠ°ΠΏΠ°Π·ΠΎΠ½Π΅:



using System;

using System.Linq;



public class Program {

public static void Main() {

Console.WriteLine(Enumerable.Range(1, 100).Sum());

}

}



β–ͺΠŸΡ€ΠΈΠΌΠ΅Π½Π΅Π½ΠΈΠ΅ Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ ΠΊΠΎ всСм числам Π² спискС:



using System;

using System.Linq;



public class Program {

private static int Square(int n) => n * n;



public static void Main() {

int[] arr = { 1, 2, 3, 4 };



// direct anonymous function

int[] arr2 = arr.Select(n => n * n).ToArray();

// using another method

int[] arr3 = arr.Select(Square).ToArray();



foreach (int n in arr2)

Console.WriteLine(n); // output: 1, 4, 9, 16

foreach (int n in arr3)

Console.WriteLine(n); // output: 1, 4, 9, 16

}

}




β–ͺΠ€ΠΈΠ»ΡŒΡ‚Ρ€Π°Ρ†ΠΈΡ списка Π½ΠΎΠΌΠ΅Ρ€ΠΎΠ²:



using System;

using System.Linq;



public class Program {

private static bool IsValid(int n) => n % 2 == 0 && n > 4;



public static void Main() {

int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };



// direct anonymous function

int[] arr2 = arr.Where(n => n % 2 == 0 && n > 4).ToArray();

// using another method

int[] arr3 = arr.Where(IsValid).ToArray();



foreach (int n in arr2)

Console.WriteLine(n); // output: 6, 8

foreach (int n in arr3)

Console.WriteLine(n); // output: 6, 8

}

}




β–ͺНахоТдСниС минимального/максимального значСния Π² спискС:



using System;

using System.Linq;



public class Program {

public static void Main() {

int[] arr = { 4, 7, 2, 1, 3, 6, 9, 8, 0, 5 };

Console.WriteLine(Enumerable.Min(arr)); // output: 0

Console.WriteLine(Enumerable.Max(arr)); // output: 9

}

}



@csharp_ci