Hexxed Hexxed - 4 years ago 131
C# Question

How can I get the List with a custom datatype to a string builder?

I have a class.

public class IdDetails
{
public string transactionDate { get; set; }
public string upnName { get; set; }
public string movementTrade { get; set; }
public string baseCurve { get; set; }
public string cTolerance { get; set; }
//17 more declarations below
}


Then I used it as the DataType of my List
Interface


foreach(DataRow r in tbl1.Rows)
{
InterFace.Add(new IdDetails
{
transactionDate = Convert.ToDateTime(r["TransDate"]).ToString(@"MM/dd/yyyy"),
upnName = string.Empty
movementTrade = "incoming",
//... Somemore adding of values
}
}


I have tried this reference. However, I think it is build of strings with Single data inside each item.I dont know the actual terminology for this

I have tried to do it like this using my reference

var x = concatenate<IdDetails>(Interface, Convert.ToString, ';');


But I'm not getting the result i need, Instead I am getting there values

//output im getting
x = "DataImport2.IdDetails;" //<- this string repeated multiple times


enter image description here

Question: How can I directly write the contents of the my custom List to a string builder? Without me transforming it to another object. Because I can cast it to a
DataTable
and process it to a
StringBuilder
. That's a rather long process and coding.

Hope someone can help me.

Answer Source

You can use string.Join() to achieve what you need. For example

string.Join(",", Interface.Select(item => item.transactionDate + " " + item.xxx + // etc etc));

EDIT:

Override ToString() in IdDetails to use Reflection to get all values of your class.

public class IdDetails
{
    public string transactionDate { get; set; }
    public string upnName { get; set; }
    public string movementTrade { get; set; }
    public string baseCurve { get; set; }
    public string cTolerance { get; set; }

    private static string SafeString(object s)
    {
        return s == null ? string.Empty : s.ToString();
    }

    public override string ToString()
    {
        PropertyInfo[] properties = typeof(IdDetails).GetProperties();
        return string.Join(",", properties.Select(prop => SafeString(prop.GetValue(this, null))).ToArray());
    }

    //17 more declarations below
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download