|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | + |
| 5 | +namespace SequenceExamples |
| 6 | +{ |
| 7 | + class Program |
| 8 | + { |
| 9 | + // This part is just for testing the examples |
| 10 | + static void Main(string[] args) |
| 11 | + { |
| 12 | + MinBy.MinByKeySelectorExample(); |
| 13 | + MinBy.MinByComparerExample(); |
| 14 | + } |
| 15 | + |
| 16 | + #region MinBy |
| 17 | + static class MinBy |
| 18 | + { |
| 19 | + public static void MinByKeySelectorExample() |
| 20 | + { |
| 21 | + // <Snippet210> |
| 22 | + (string Name, decimal Salary, int Age)[] employees = |
| 23 | + { |
| 24 | + ("Mahmoud", 1000m, 22), |
| 25 | + ("John", 1200m, 28), |
| 26 | + ("Sara", 2000m, 32), |
| 27 | + ("Hadi", 1750m, 27), |
| 28 | + ("Lana", 1500m, 24), |
| 29 | + ("Luna", 1850m, 33) |
| 30 | + }; |
| 31 | + |
| 32 | + // Get the youngest employee in the company. |
| 33 | + var youngestEmployee = employees.MinBy(employee => employee.Age); |
| 34 | + |
| 35 | + Console.WriteLine($"Name: {youngestEmployee.Name}, Age: {youngestEmployee.Age}, Salary: ${youngestEmployee.Salary}"); |
| 36 | + |
| 37 | + /* |
| 38 | + This code produces the following output: |
| 39 | +
|
| 40 | + Name: Mahmoud, Age: 22, Salary: $1000 |
| 41 | + */ |
| 42 | + // </Snippet210> |
| 43 | + } |
| 44 | + |
| 45 | + public static void MinByComparerExample() |
| 46 | + { |
| 47 | + // <Snippet211> |
| 48 | + (string Name, int Quantity)[] inventory = |
| 49 | + { |
| 50 | + ("apple", 10), |
| 51 | + ("BANANA", 5), |
| 52 | + ("Cherry", 20) |
| 53 | + }; |
| 54 | + |
| 55 | + // Find the product with the minimum name alphabetically, ignoring casing differences. |
| 56 | + // 'a' is correctly identified as smaller than 'B' when case is ignored. |
| 57 | + var minIgnoreCase = inventory.MinBy(item => item.Name, StringComparer.OrdinalIgnoreCase); |
| 58 | + Console.WriteLine($"Case-insensitive comparison: {minIgnoreCase.Name}"); |
| 59 | + |
| 60 | + /* |
| 61 | + This code produces the following output: |
| 62 | +
|
| 63 | + Case-insensitive comparison: apple |
| 64 | + */ |
| 65 | + // </Snippet211> |
| 66 | + } |
| 67 | + } |
| 68 | + #endregion |
| 69 | + } |
| 70 | +} |
0 commit comments