Blog Consulting CodeHelper About

Generic Methods with Generic Parameters in c#

The challenge: Make a method to calculate the Min. Difference in a list of numbers.
The challenge Make a method to calculate the Min. Difference in a list of numbers. So we are looking to create a truly generic method

The Code

public static T MinDifference<T>(this IEnumerable<T> numbers) 
{
int count = 1;
var _n = numbers.Cast<dynamic>().ToList();
_n.Sort();
return (T)_n.Skip(1).Min(n => n - _n[count++ - 1]);
}

Explanation

Result

List<int> _dividors = _n.GetAllDividors().ToList();
_dividors.MinDifference();

HashSet<double> _ht = new HashSet<double>();
_ht .Add(1.1);
_ht .Add(0.2);
_ht .Add(0.4);
_ht .Add(1);
_ht .Add(0.1);
double _r1 = _t1.MinDifference();

decimal[] _dec = new decimal[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var _rdec = _dec.MinDifference();

Array _dividors2 = _dividors .GetAllDividors().ToArray();
_dividors2.MinDifference();
Whatever type of list of numbers you use, the size of the list, you used 1 method.

Related .Net Articles