From Parameter to Property?
public class ConcatenateListTMember
{
public static void Test()
{
var someList = new List<AnyClass>();
someList.Add(new AnyClass("value1"));
someList.Add(new AnyClass("value2"));
Console.WriteLine(Concatenate(someList, "SomeProperty"));
Console.ReadLine();
}
static string Concatenate<T>(List<T> list, string specifiedPropertyOfT)
{
string output = String.Empty;
// TODO: Somehow concatenate all the specified property elements in the list?
return output;
}
}
internal class AnyClass
{
public AnyClass(string someProperty)
{
SomeProperty = someProperty;
}
public string SomeProperty { get; set; }
}
How might it be possible to implement the generic method in this code sample?
- Please note that
specifiedPropertyOfTdoes not have to be a string if the same aim can be achieved using another type. - Ideally, reflection would not be needed 🙂
Even better – an extension method:
Usage:
Live example: http://rextester.com/runcode?code=LRA78268