I want to develop a Generic Extension Method which should arrange the string in alphabetical then by lengthwise ascending order.
I mean
string[] names = { "Jon", "Marc", "Joel", "Thomas", "Copsey","Konrad","Andrew","Brian","Bill"}; var query = names.OrderBy(a => a.Length).ThenBy(a => a);
What is the way to develop Generic Extension Method?
I tried :
public static class ExtensionOperation { public static T[] AlphaLengthWise<T>(this T[] names) { var query = names.OrderBy(a => a.Length).ThenBy(a => a); return query; } }
I received :
Error 1: T does not contain definition for Length
Error 2: can not convert
System.Linq.IOrderedEnumerable
toT[]
.
Generics are a way to tailor a class or method to a specific type. A generic method or class is designed to work for any type. This is most easily illustrated in the List<T> class, where it can be tailored to be a list of any type. This gives you the type-safety of knowing the list only contains that specific type.
An extension method must be defined in a top-level static class. An extension method with the same name and signature as an instance method will not be called. Extension methods cannot be used to override existing methods. The concept of extension methods cannot be applied to fields, properties or events.
You can create an instance of generic classes by specifying an actual type in angle brackets. The following creates an instance of the generic class DataStore . DataStore<string> store = new DataStore<string>(); Above, we specified the string type in the angle brackets while creating an instance.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
The first error is because Length
is a property of the String
class while in your generic version the type of the T parameter is not known. It could be any type.
The second error is because you return just the query object but not the actual result. You might need to call ToArray()
before returning.
With little modifications you could come up with this:
public static class ExtensionOperation { public static IEnumerable<T> AlphaLengthWise<T, L>( this IEnumerable<T> names, Func<T, L> lengthProvider) { return names .OrderBy(a => lengthProvider(a)) .ThenBy(a => a); } }
Which you could use like this:
string[] names = { "Jon", "Marc", "Joel", "Thomas", "Copsey", "Konrad", "Andrew", "Brian", "Bill" }; var result = names.AlphaLengthWise(a => a.Length);
Why do you want to do this generically? Just use
public static class ExtensionOperations { public static IEnumerable<string> AlphaLengthWise(this string[] names) { var query = names.OrderBy(a => a.Length).ThenBy(a => a); return query; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With