Based on what you said i assume you already have a predefined way of choosing which property to write for a given object.Making this assumption :
class FooItem
{
public string Name{get;set;}
public double Volume{get;set;}
}
public void WriteFoos(IEnumerable<(string,FooItem)>inventory,string fileName){
StringBuilder sb = new StringBuilder();
foreach(var item in inventory) {
WriteFoo(item,sb);
}
File.WriteAllText(fileName,sb);
}
public void WriteFoo((FooItem item,string property)pair,StringBuilder sb){
object value=ChooseProperty(pair);
sb.AppendFormat("{0},{1}", pair.property,value);
}
public object ChooseProperty((FooItem item,string property)pair){
switch(property){
case "Volume":return pair.item.Volume;
case "Name":return pair.item.Name;
}
}
P.S Choosing the property based on a given string
with a switch-case
is the most easy way.If you want something generic (without having to write the switch-case
you can change the ChooseProperty
using System.Reflection
like:
public object ChooseProperty((FooItem item,string property)pair){
PropertyInfo prop=pair.item.GetType().GetProperty(pair.property);
object value=prop.GetValue(item);
return value;
}
This however will cause you a performance hit.Another variant is to use System.Linq.Expressions