How to refactor these 2 similar methods into one?

前端 未结 3 1515
执念已碎
执念已碎 2021-02-10 00:36

I\'ve seen some samples of using \'T\' to make a method reuseable for generic collections of different classes, but I\'ve never really gotten into it or understood the samples.

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-10 00:55

    Without implementiong a common interface like @Grzenio suggested, you could use a generic method like this:

        public List ToSelectList(IEnumerable enumerable, Func text, Func value, string defaultOption)
        {
            var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList();
            items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" });
            return items;
        }
    
        // use like
    
        t.ToSelectList(departments, d => d.Code + " - " + d.Description, d => d.Id.ToString(), "default");
        t.ToSelectList(functions, f => f.Description, f => f.Id.ToString(), "default");
    

提交回复
热议问题