James Buckingham
James Buckingham

Reputation: 815

Customised method for List collection based on a type

Is there a way of extending the C# List class that would allow me to attach a custom method specific for one type?

In my example I have a List of LatestNews objects. Each of these contains a property of type Category.

What I want to do is attach a custom method to the List<> that would return all unique Category objects within the collection of LatestNews.

I have the following working using Generics but I noticed that if I then declare a List<> of a different type (i.e. string) this method is made available.

public static List<LatestNewsCategory> getUniqueCategories<T>(this IList<T> list) 
{
    List<LatestNewsCategory> catList = new List<LatestNewsCategory>();
    List<LatestNews> myNewsList = (List<LatestNews>)list;

    foreach (LatestNews news in myNewsList)
    {
        if (catList.Find(LatestNewsCategory => LatestNewsCategory.ID == news.Category.ID) == null)
        {
            catList.Add(news.Category);
        }
    }

    return catList;
}

Is there a different approach I should be taking with this?

Should I maybe look at creating a custom class that extends List instead?

Thanks

Upvotes: 0

Views: 64

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236328

Parametrize your list with LatestNews type if you want this extension to be available only to list of LatestNews:

public static List<LatestNewsCategory> getUniqueCategories(
    this IList<LatestNews> list) 
{
    // ...
}

Side note 1 - we use PascalCase names for public members, e.g. GetUniqueCategories

Side note 2 - you can use LINQ to get distinct categories from list of latest news:

return list.Select(n => n.Category)
           .GroupBy(c => c.ID)
           .Select(g => g.First())
           .ToList();

Or if you have Equals and GetHashCode overridden on LatestNewsCategory type, then you can simply

return list.Select(n => n.Category).Distinct().ToList();   

Side note 3 - you can create extension for IEnumerable<LatestNews> thus you just enumerating list items.

Upvotes: 0

pid
pid

Reputation: 11607

Have you tried to derive? If you do this, try to keep it on the generic side of things, like this:

class SpecializedList<T> extends List<T>
{
    // put your specialized generic<T> methods here
}

That may be a good thing to reuse code, but sincerely this makes more sense when you have say 2 or 3 specialized methods.

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 157116

You should change your generic type in the signature.

Change it so something like this:

public static List<LatestNewsCategory> getUniqueCategories(this IList<LatestNews> list) 

Upvotes: 2

Related Questions