Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing custom indexer on a collection

Tags:

c#

c#-4.0

I want to make a custom indexer on a collection. Here are my classes:

Business Class:

public class UserCollection : Collection<User>
{
    public new User this[int index]
    {
        get
        {
            return this.FirstOrDefault(x => x.UserID == index);
        }
    }

}

BL API Method:

public static Collection<User> GetUser()
{
    return new UserCollection
               {
                   new User {UserID = 2},
                   new User {UserID = 4}
               };
}

Usage:

  Collection<User> users = GetUser();
    User user = users[2];

    }

User class has few columns like UserID, UserName etc. I want to fetch a user from collection via index and here index will be user id. But the above usage code is not doing it, and it is considering indexer of parent Collection class. I want my custom indexer to come into play. I can do it by exposing UserCollection as the return type of GetUser method and then the solution will be to use the code like this

UserCollection users = GetUser();

But I am thinking to return the most general type from BL method here which is Collection. How can I solve this issue?

like image 467
Rocky Singh Avatar asked Feb 21 '23 23:02

Rocky Singh


1 Answers

Read the documentation for Collection<T> carefully paying close attention to the 'Notes to Inheritors' section. It will link to another page that gives you an example of doing what you're trying to do.

You might also want to check out the KeyedCollection<TKey, TItem> class which might make things a bit easier on you. Your custom class would simply become:

public class UserCollection: KeyedCollection<int, User>
{

    public UserCollection() : base() {}

    protected override int GetKeyForItem(User user)
    {
        return user.UserID;
    }
}
like image 57
Justin Niessner Avatar answered Mar 05 '23 01:03

Justin Niessner