Avatar of flynny
flynny
Flag for United Kingdom of Great Britain and Northern Ireland asked on

C# Generic Extension Method Help

Hi All,

I am trying to create a generic extension method for converting a List<T> to a List<SelectListItem> for dropdown lists in the view.

Now, I have the following Generic Repository System

    public interface IRepository<T>
    {
        void Insert(T entity);
        void Update(T entity);
        void Delete(T entity);
        IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
        IQueryable<T> GetAll();
        IOrderedEnumerable<T> GetPage(int pageIndex, int pageSize, string sortBy, string sortDirection);
        T GetById(int id);
    }

Open in new window


   public class Repository<T> : IRepository<T> where T : class, IEntity
    {
        protected Table<T> DataTable;

        public Repository(DBDataContext dataContext)
        {
            DataTable = dataContext.GetTable<T>();
        }
        
        public Repository(DataContext dataContext)
        {
            DataTable = dataContext.GetTable<T>();
        }

        #region IRepository<T> Members

        public void Insert(T entity)
        {
            DataTable.InsertOnSubmit(entity);
        }

        public void Update(T entity)
        {
            DataTable.Attach(entity, true);
        }

        public void Delete(T entity)
        {
            DataTable.DeleteOnSubmit(entity);
        }

        public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
        {
            return DataTable.Where(predicate);
        }

        public IQueryable<T> GetAll()
        {
            return DataTable;
        }

        public IOrderedEnumerable<T> GetPage(int pageIndex = 0, int pageSize = 10, string sortBy = "ID", string sortDirection = "asc")
        {
            var param = Expression.Parameter(typeof(T));

            var sortExpression = Expression.Lambda<Func<T, object>>
                (Expression.Convert(Expression.Property(param, sortBy), typeof(object)), param).Compile();

            var results = DataTable.Skip((pageIndex - 1)*pageSize).Take(pageSize);

            switch (sortDirection.ToLower())
            {
                case "asc":
                    return results.OrderBy(sortExpression);
                default:
                    return results.OrderByDescending(sortExpression);
            }
        }

        public T GetById(int id)
        {
            return DataTable.Single(e => e.ID.Equals(id));
        }

        #endregion
    }

Open in new window


Where I entity is simply enforcing the ID

    public interface IEntity
    {
        int ID { get; }
    }

Open in new window


All the classes in my DBML are implementing IEntity.

and My Extensions Class is simply;

public static class RepositoryExtensions
    {
       public static IEnumerable<SelectListItem> ToSelectListItems<T>(
            this IEnumerable<T> items,
            Func<T, string> nameSelector,
            Func<T, string> valueSelector,
            Func<T, bool> selected)
       {
           return items.OrderBy(item => nameSelector(item))
                  .Select(item =>
                          new SelectListItem
                          {
                              Selected = selected(item),
                              Text = nameSelector(item),
                              Value = valueSelector(item)
                          });
       }
    }

Open in new window


Now for example when I try to get a dropdown list for all countries in my datbase as an example I have and call the following method

public static List<Country> GetCountries()
        {
            using (DBDataContext db = new DBDataContext())
            {
                return db.Countries.OrderBy(c => c.NiceName).ToList();
            }
        }

Open in new window


which I implment in the view as follows;

@Html.DropDownListFor(x => x.ID, Core.MiscRepository.GetCountries().ToSelectListItems("ID", "NiceName", true))

Open in new window


however, its not finding the extension method? Could anyone point me in the right direction please?

Many Thanks in Advance,

Matt.
C#.NET ProgrammingProgramming

Avatar of undefined
Last Comment
kaufmed

8/22/2022 - Mon
Gururaj Badam

Try including the extension method namespace in the Controller file where you have GetCountries defined.
ASKER CERTIFIED SOLUTION
kaufmed

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy