Express C# generic type arguments more succinctly? -
inspired
comparing 2 collections equality irrespective of order of items in them
i created extension method test whether 2 collections equivalent. use extension method, have specify 2 type parameters this:
isequivalenttotesthelper<observablecollection<string>, string>(first, second, true);
is there way implement extension method 1 generic constraint (e.g. observablecollection<string>
) need specified?
update: posted modified code based on answers additional response question inspired one.
here's original code:
static public class enumerableextensions { static public bool isequivalentto<e,t>(this e first, e second) e : ienumerable<t> { if ((first == null) != (second == null)) return false; if (!object.referenceequals(first, second) && (first != null)) { if (first.count() != second.count()) return false; if ((first.count() != 0) && havemismatchedelement<e,t>(first, second)) return false; } return true; } private static bool havemismatchedelement<e,t>(e first, e second) e : ienumerable<t> { int firstcount; int secondcount; var firstelementcounts = getelementcounts<e,t>(first, out firstcount); var secondelementcounts = getelementcounts<e,t>(second, out secondcount); if (firstcount != secondcount) return true; foreach (var kvp in firstelementcounts) { firstcount = kvp.value; secondelementcounts.trygetvalue(kvp.key, out secondcount); if (firstcount != secondcount) return true; } return false; } private static dictionary<t, int> getelementcounts<e,t>(e enumerable, out int nullcount) e : ienumerable<t> { var dictionary = new dictionary<t, int>(); nullcount = 0; foreach (t element in enumerable) { if (element == null) { nullcount++; } else { int num; dictionary.trygetvalue(element, out num); num++; dictionary[element] = num; } } return dictionary; } static private int gethashcode<e,t>(ienumerable<t> enumerable) e : ienumerable<t> { int hash = 17; foreach (t val in enumerable.orderby(x => x)) hash = hash * 23 + val.gethashcode(); return hash; } }
static public bool isequivalentto<t>(this ienumerable<t> first, ienumerable<t> second)
Comments
Post a Comment