0

我有以下代码来生成选择列表项以显示在我的下拉列表中。

public static IEnumerable<SelectListItem> ToSelectListItems(this IEnumerable<BlogCategory>    categories, int selectedId)
    {
        return categories.OrderBy(category => category.Category)
            .Select(category => new SelectListItem
            {
                Selected = (category.ID == selectedId),
                Text = category.Category,
                Value = category.ID.ToString()
            });
    }

我想使用这个助手类来生成其他列表项,然后是 BlogCategory。我怎样才能做到这一点?

4

2 回答 2

3

您可以为查找实体创建一个基类:

public class BaseEntity
{
   public int Id {get;set;}
   public string Title {get;set;}
}

public class Category : BaseEntity
{
   //Category fields
}

public class Blog : BaseEntity
{
   //Blog fields
}  

public static IEnumerable<SelectListItem> ToSelectListItems(this IEnumerable<BaseEntity> entityList, int selectedId)
{
    return entityList.OrderBy(q => q.Title)
        .Select(q => new SelectListItem
        {
            Selected = (q.Id == selectedId),
            Text = q.Title,
            Value = q.Id.ToString()
        });
}
于 2012-07-20T13:24:21.187 回答
2

于尔根,

假设您的意思是其他列表项都符合与 BlogCategory 相同的结构,那么您可以使用接口,而不是帮助程序中的具体类。

这可能是这样的:

public interface ICategory
{
    int ID { get; set; }
    string Category { get; set; }
}

public class BlogCategory : ICategory
{
    public int ID { get; set; }
    public string Category { get; set; }
} 

public class PostCategory : ICategory
{
    public int ID { get; set; }
    public string Category { get; set; }
} 

等等,等等。然后根据需要使用您现有的帮助程序类,使用您的其他类来对抗这个接口:

public static IEnumerable<SelectListItem> ToSelectListItems
    (this IEnumerable<ICategory> categories, int selectedId)
{
    return categories.OrderBy(category => category.Category)
        .Select(category => new SelectListItem
        {
            Selected = (category.ID == selectedId),
            Text = category.Category,
            Value = category.ID.ToString()
        });
}

请享用...

于 2012-07-20T13:34:07.567 回答