elena1234

FilterByAge - how to use predicate (Func<>)

Jan 22nd, 2021 (edited)
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.25 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace FilterByAge
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             int n = int.Parse(Console.ReadLine());
  12.             var listOfStudents = new List<Student>();
  13.             for (int i = 0; i < n; i++)
  14.             {
  15.                 var inputArray = Console.ReadLine().Split(", ", StringSplitOptions.RemoveEmptyEntries);
  16.                 string name = inputArray[0];
  17.                 int age = int.Parse(inputArray[1]);
  18.                 Student newStudent = new Student(name, age);
  19.                 listOfStudents.Add(newStudent);
  20.             }
  21.  
  22.             string firstCondition = Console.ReadLine();
  23.             int secondCondition = int.Parse(Console.ReadLine());
  24.             string formatToPrint = Console.ReadLine();
  25.  
  26.             Func<Student, bool> predicate = null;
  27.             if (firstCondition == "older")
  28.             {
  29.                 predicate = s => s.Age >= secondCondition;
  30.             }
  31.  
  32.             else if (firstCondition == "younger")
  33.             {
  34.                 predicate = s => s.Age < secondCondition;
  35.             }
  36.  
  37.             var filtertedList = listOfStudents.Where(predicate);
  38.  
  39.             foreach (var student in filtertedList)
  40.             {
  41.                 switch (formatToPrint)
  42.                 {
  43.                     case "name age":
  44.                         {
  45.                             Console.WriteLine($"{student.Name} - { student.Age}");
  46.                             break;
  47.                         }
  48.  
  49.                     case "name":
  50.                         {
  51.                             Console.WriteLine(student.Name);
  52.                             break;
  53.                         }
  54.  
  55.                     case "age":
  56.                         {
  57.                             Console.WriteLine(student.Age);
  58.                             break;
  59.                         }
  60.  
  61.                     default:
  62.                         break;                    
  63.                 }
  64.             }
  65.         }
  66.     }
  67. }
  68.  
  69.  
  70. class Student
  71. {
  72.     public string Name { get; set; }
  73.     public int Age { get; set; }
  74.  
  75.     public Student(string Name, int Age)
  76.     {
  77.         this.Name = Name;
  78.         this.Age = Age;
  79.     }
  80. }
  81.  
Add Comment
Please, Sign In to add comment