Design for letting user select properties to write to a CSV file

I have a list of objects where the object type has about 60 properties. The user wants to be able to export this list to a CSV file with only the properties they choose. I'm trying to think of a better design than just a huge if/else statement (bound to a checkbox for each property that the user can check/uncheck) and building each line. Open to any ideas 🙂
4 Replies
mtreit
mtreit•9mo ago
If you have that many properties, consider using reflection.
Nacho Man Randy Cabbage
Nacho Man Randy CabbageOP•9mo ago
Hmm, so I could make a class to hold the property name and "ischecked" for each property in the class, and get all those properties using reflection. Then when I'm ready to write the csv I could use linq and reflection to get the real property value based on the name...I think? Think that makes sense. Thank you 🙂
mtreit
mtreit•9mo ago
Yeah, or something like this:
static List<(string, string)> GetProperties<T>(T item, HashSet<string> desiredProperties)
{
var properties = typeof(T).GetProperties();

var result = new List<(string, string)>();
foreach (var property in properties)
{
if (desiredProperties.Contains(property.Name))
{
result.Add((property.Name, property.GetValue(item).ToString()));
}
}

return result;
}
static List<(string, string)> GetProperties<T>(T item, HashSet<string> desiredProperties)
{
var properties = typeof(T).GetProperties();

var result = new List<(string, string)>();
foreach (var property in properties)
{
if (desiredProperties.Contains(property.Name))
{
result.Add((property.Name, property.GetValue(item).ToString()));
}
}

return result;
}
That assumes everything is a string, you might need to make it more intelligent to also have the property type encoded in a second type parameter or something like that. Although if you're writing to a CSV it's all going to turn into strings anyway.
Nacho Man Randy Cabbage
Nacho Man Randy CabbageOP•9mo ago
hmm yeah they aren't all strings but they will be in teh end anyways yup sweet, will give this a shot, thank you
Want results from more Discord servers?
Add your server