Home > front end >  Extension Method for List<T> with return type T
Extension Method for List<T> with return type T

Time:10-15

I want to create an extension method for List<T> type so I can Limit, Order and Page my data within it.

So far I've create a static class like this:

public static class DataTools {
    public static List<T> ToPaging(this List<T> list, int PageNumber,int Count,string OrderField,OrderType OrderType) {
        return null;
    }
}

but I get an error indicating that the type or namespace T could not be found .

When I make my class generic like this:

public static class DataTools<T> {
    public static List<T> ToPaging(this List<T> list, int PageNumber,int Count,string OrderField,OrderType OrderType) {
        return null;
    }
}

This time I get an error that says: extension method must be defined in a non-generic static class .

I don't know what to do. I just want to create an extension method to "Page"ilize my data before sending it to front.

CodePudding user response:

Specify the generic parameter on the method, not the class:

public static class DataTools
{
    public static List<T> ToPaging<T>(this List<T> list, int PageNumber,
        int Count, string OrderField,OrderType OrderType)
    {
        return null;
    }
}

Instead of specifying the field by name, which can be misspelled, one could use a Func<TSource,TKey> like LINQ :

public static class DataTools
{
    public static List<T> ToPaging<T>(this List<T> list, int PageNumber,
        int Count, Func<T,TKey> selector,OrderType OrderType)
    {
        var query=(orderType == OrderType.Ascending)
                   ? list.OrderBy(selector)
                   : list.OrderByDescending(selector);
        return query.Skip( (PageNumber-1)*Count)
                    .Take(Count)
                    .ToList();
    }
}

Assuming there's a list of Customer objects :

class Customer
{
    public int Id {get;set;}
    public string Name{get;set;}
    public string Address {get;set;}
}

...
var list=new List<Customer>();

The list can be paged with :

var page=list.ToPaging(0,10, c=>c.Id, OrderType.Ascending);

or

var page=list.ToPaging(0,10, c=>c.Name, OrderType.Ascending);

CodePudding user response:

Based on this you need to considerer following points when creating an extension method:

  1. The class which defines an extension method must be non-generic, static and non-nested

  2. Every extension method must be a static method

  3. The first parameter of the extension method should use the this keyword.

So the result would be like this:

public static class DataTools
{
    public static List<T> ToPaging<T>(this List<T> list, int PageNumber,
        int Count, string OrderField,OrderType OrderType)
    {
        return null;
    }
}
  • Related