.NET 4.x Создание расширенных методов для любой коллекции, делегаты - C#
Формулировка задачи:
Нужна скорая помощь!)
У меня вот такой класс:
и такая программа:
Расширенный метод max работает с массивами типа int, а нужно, чтобы он работал со всеми коллекциями(IEnumerable). С перегрузками получается, но код длинный, подскажите короткий вариант этой функции)
И нужна функция T Select(bool condition, T item), которая возвращает коллекцию тех элементов из заданной коллекции, которые соответствуют условию.
P.S. я преднамеренно удалила System.Linq, нам задали писать свои функции : D
Листинг программы
- using System;
- using System.Text;
- namespace ConsoleApplication1
- {
- public static class Functions
- {
- public static bool IsEven(int a)
- {
- return a % 2 == 0;
- }
- public static bool IsOdd(int a)
- {
- return a % 2 != 0;
- }
- public static int max(this int[] arr, del dl = null)
- {
- int max=arr[0];
- if (dl != null)
- {
- foreach (int item in arr)
- if (dl(item))
- if (!dl(max) || max < item)
- max = item;
- if (!dl(max))
- throw new Exception("No specified type of elements");
- }
- else
- foreach (int item in arr)
- if (max < item)
- max = item;
- return max;
- }
- }
- }
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace ConsoleApplication1
- {
- public delegate bool del(int a);
- class Program
- {
- static void Main(string[] args)
- {
- del IsEven = Functions.IsEven;
- del IsOdd = Functions.IsOdd;
- int[] a = new int[]{32492435,431,534,623,44,999};
- Console.WriteLine(a.max());
- Console.WriteLine(a.max(IsEven));
- Console.WriteLine(a.max(IsOdd));
- }
- }
- }
Решение задачи: «.NET 4.x Создание расширенных методов для любой коллекции, делегаты»
textual
Листинг программы
- public static class Functions
- {
- public static T Max<T>(this IEnumerable<T> source, IComparer<T> comparer = null)
- {
- if (source == null)
- throw new ArgumentNullException("source");
- comparer = comparer ?? Comparer<T>.Default;
- return Max(source, comparer.Compare);
- }
- public static T Max<T>(this IEnumerable<T> source, Comparison<T> cmp)
- {
- if (source == null)
- throw new ArgumentNullException("source");
- if(cmp == null)
- throw new ArgumentNullException("cmp");
- T max = default(T);
- if (max == null)
- {
- foreach (T s in source)
- if ((s != null) && ((max == null) || (cmp(s, max) > 0)))
- max = s;
- return max;
- }
- bool flag = false;
- foreach (T s in source)
- {
- if (flag)
- {
- if (cmp(s, max) > 0)
- max = s;
- }
- else
- {
- max = s;
- flag = true;
- }
- }
- if (!flag)
- {
- throw new Exception("No Elements");
- }
- return max;
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д