Entity Framework 4: Generic return type for a method
I have the following code -
var db =开发者_开发技巧 new DBEntities();
var entity = //get entity;
lblName.Text = string.Empty;
var names = entity.Names.OrderBy(x => x.Value).ToList();
for (var i = 0; i < names .Count; i++)
{
if (i == names .Count - 1) lblName.Text += names [i].Value + ".";
else lblName.Text += names [i].Value + ", ";
}
I'll have several For loops like above which will format the value to be displayed in a label. I'm trying to make a method out of it which will do the formatting when I pass in the collection and the label, something like -
void FormatValue(List<??> items, Label label)
{
//For loop
//Format value
}
What do I pass in for the List. How do I make this generic enough so I'll be able to use it for all entity.Names
, entity.Xxx
, entity.Yyy
etc?
Make the method itself generic and allow the caller to specify a formatter:
void FormatValue<T>(List<T> items, Label label, Func<string, T> formatter)
{
foreach(var item in items)
{
label.Text += formatter(item);
}
}
You can then call the method like:
FormatValue<Name>(entity.Names.OrderBy(x => x.Value).ToList(),
lblName,
i => i.Value + ", ");
精彩评论