Bertrand Paul Bertrand Paul - 11 days ago 5
C# Question

generic creation of a comma separated string list from a collection

I have the following code. The first line should be the comma separated headers string and the remaining should be the content of my collection layed out to be written to a comma separated file. How do i get the values out?

public static List<string> ToListOfStrings<T>(this List<T> items, string sep)
{
var NewList = new List<string>();
//string tempHeaderString = "";

PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

string s = string.Empty;
foreach (var prop in props)
{
s += prop.Name + sep;

}
NewList.Add(s + System.Environment.NewLine);
foreach (var item in items)
{
string s1 = string.Empty;
var values = new object[props.Length];
for (var i = 0; i < props.Length; i++)
{
s1 += (props[i].GetValue(item, null)).ToString() + sep;
}

NewList.Add(s1 + System.Environment.NewLine);
}

return NewList;
}


My target Object T only has strings as member properties.

Best

B

Answer

As far as I understand from comment only problem in your code is string representation of property value. I've simplified code a bit and created special method where you can place logic to convert value to string, or you can just overload ToString() method for type if it's your types in properties.

    public static IEnumerable<string> ToListOfStrings<T>(this List<T> items, string sep)
    {
        var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        yield return properties.Select(p => p.Name).CreateRow(sep);

        foreach (var item in items)
        {
            yield return properties.Select(p => GetString(p.GetValue(item, null))).CreateRow(sep);
        }
    }

    private static string CreateRow(this IEnumerable<string> values, string separator)
    {
        return string.Join(separator, values) + System.Environment.NewLine;
    }

    public static string GetString(object obj)
    {
        //custom logic to create string from values
        return obj.ToString();
    }
Comments