如何编写通用 IEnumerable扩展方法
我对仿制药相当陌生(好吧,真的很新),但我喜欢它们的想法。我将在视图上有一些下拉列表,我想要一种通用的方法来获取对象列表并将其转换为 SelectListItems
列表
我现在拥有的:
public static IEnumerable<SelectListItem> ToSelectListItems(
this IEnumerable<SpecificObject> items, long selectedId)
{
return
items.OrderBy(item => item.Name)
.Select(item =>
new SelectListItem
{
Selected = (item.Id == selectedId),
Text = item.Name,
Value = item.Id.ToString()
});
}
麻烦是,我需要为每个下拉列表重复该代码,因为对象具有代表 SelectListItem
的 Text
属性的不同字段,
这就是我想要的完成:
public static IEnumerable<SelectListItem> ToSelectListItem<T>(this IEnumerable<T> items, string key, string value, int SelectedId) {
// I really have no idea how to proceed from here :(
}
I'm fairly new (ok, REALLy new) to generics but I love the idea of them. I am going to be having a few drop-down lists on a view and I'd like a generic way to take a list of objects and convert it to a list of SelectListItems
What I have now:
public static IEnumerable<SelectListItem> ToSelectListItems(
this IEnumerable<SpecificObject> items, long selectedId)
{
return
items.OrderBy(item => item.Name)
.Select(item =>
new SelectListItem
{
Selected = (item.Id == selectedId),
Text = item.Name,
Value = item.Id.ToString()
});
}
Trouble is, I'd need to repeat that code for each drop-down as the objects have different fields that represent the Text
property of the SelectListItem
Here is what I'd like to accomplish:
public static IEnumerable<SelectListItem> ToSelectListItem<T>(this IEnumerable<T> items, string key, string value, int SelectedId) {
// I really have no idea how to proceed from here :(
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以传入委托来进行比较和属性检索。像这样:
然后你会像这样使用它:
You could pass in delegates to do the comparisons, and property retrieval. Something like this:
Then you would use it like so:
为了使其按照书面方式工作,您的类型
T
将需要实现一些提供Name
和Id
属性的接口:有了这个,您可以执行以下操作:
这是为了在扩展方法中使用
Name
和Id
属性所必需的...相反,您可以提供一种不同的方式来接收这些属性(即:传递代表),但这可能会也可能不会增加您场景中的维护成本。In order for this to work as written, your type
T
will need to implement some interface which providesName
andId
properties:With this in place, you can do:
This is required in order to use the
Name
andId
properties within your extension method... You could, instead, provide a different means of receiving these (ie: passing delegates), but that may or may not increase the maintenance cost in your scenario.//需要使用反射来获取值
//You need to use reflection to get the value of
好吧,你可以这样做:
Well, you could do something like this: