I’ve been writing this out a few different places in my code and I want to create a single, generic function, but I can’t quite figure out how.
Here is an example of what I’m doing:
public static string FormatCompaniesAsCSV(ICollection<Company> companies)
{
string csv = "";
foreach(Company c in companies)
{
csv += c.CompanyName + ",";
}
return csv.Substring(0, csv.LastIndexOf(","));
}
The problem is that I have to write essentially the same code if I want to display all company SKUs or all of the factories where this is manufactured. The only thing that changes is the object type and the property I am accessing. What I would like to do is something like the following:
public static string FormatCSV<T>(ICollection<T> elements, string propertyName)
{
string csv = "";
foreach(T element in elements)
{
//I know this next line doesn't work
//this is just a high level conceptualization of what I want to do
csv += element.getPropertyValue(propertyName) + ",";
}
return csv.Substring(0, csv.LastIndexOf(","));
}
I need some way to access the properties of the element in the foreach loop, but I don’t really know where to start. I’ve briefly looked at the System.Linq.Expressions library, but I didn’t find quite what I was looking for there.
Am I on the right track? If not, is there a better way to accomplish what I would like to do?
I suggest you pass in a delegate:
You can call this method like this:
You could even create an extension method out of it by adding
thisbefore the type of the first parameter:Now you can call it like this:
BTW: I changed the type from
ICollection<T>toIEnumerable<T>as you are only using features ofIEnumerable<T>.And you can improve the generation of the CSV string: