Advertisement
gabi11

Functional Programming - 5. Filter By Age

May 25th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.84 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6.  
  7.  
  8. namespace CSharpAdvanced
  9. {
  10.     public class Person
  11.     {
  12.         public string Name { get; set; }
  13.  
  14.         public int Age { get; set; }
  15.     }
  16.  
  17.     class Program
  18.     {
  19.         static void Main(string[] args)
  20.         {
  21.             int number = int.Parse(Console.ReadLine());
  22.  
  23.             var people = new List<Person>();
  24.  
  25.             for (int i = 0; i < number; i++)
  26.             {
  27.                 var input = Console.ReadLine()
  28.                     .Split(", ", StringSplitOptions.RemoveEmptyEntries);
  29.  
  30.                 var person = new Person
  31.                 {
  32.                     Name = input[0],
  33.                     Age = int.Parse(input[1])
  34.                 };
  35.  
  36.                 people.Add(person);
  37.             }
  38.  
  39.             string condition = Console.ReadLine();
  40.             int age = int.Parse(Console.ReadLine());
  41.  
  42.             Func<Person, bool> filterPredicate;
  43.  
  44.             if (condition == "older")
  45.             {
  46.                 filterPredicate = p => p.Age >= age;
  47.             }
  48.  
  49.             else
  50.             {
  51.                 filterPredicate = p => p.Age < age;
  52.             }
  53.  
  54.             string format = Console.ReadLine();
  55.  
  56.             Func<Person, string> printFunc;
  57.  
  58.             if (format == "name age")
  59.             {
  60.                 printFunc = p => $"{p.Name} - {p.Age}";
  61.             }
  62.  
  63.             else if (format == "name")
  64.             {
  65.                 printFunc = p => $"{p.Name}";
  66.             }
  67.  
  68.             else
  69.             {
  70.                 printFunc = p => $"{p.Age}";
  71.             }
  72.  
  73.             people
  74.                 .Where(filterPredicate)
  75.                 .Select(printFunc)
  76.                 .ToList()
  77.                 .ForEach(Console.WriteLine);
  78.         }
  79.     }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement