Reputation: 252
I have this class/object below:
public class Person
{
public string FirstName;
public string MI;
public string LastName;
}
Person p=new Person();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
Is there any built in in linq or c# or in subsonic that will create an output of this?:
string myString = "FirstName=\"Jeff\" p.MI=\"A\" p.LastName=\"Price\"";
Upvotes: 1
Views: 243
Reputation: 48265
It seems you need a ToString
overload in Person
. Also, don't expose public fields like that. Use properties.
public class Person
{
public string FirstName { get; set; }
public string MI { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return "FirstName=\"" + FirstName + "\" p.MI=\"" + MI + "\" p.LastName=\"" + LastName + "\"";
}
}
(edit)
Here's your request (but it requires properties):
public static class ObjectPrettyPrint
{
public static string ToString(object obj)
{
Type type = obj.GetType();
PropertyInfo[] props = type.GetProperties();
StringBuilder sb = new StringBuilder();
foreach (var prop in props)
{
sb.Append(prop.Name);
sb.Append("=\"");
sb.Append(prop.GetValue(obj, null));
sb.Append("\" ");
}
return sb.ToString();
}
}
Usage:
Console.WriteLine(ObjectPrettyPrint.ToString(new Person { FirstName, = "A", MI = "B", LastName = "C" }));
Upvotes: 2
Reputation: 25277
Well, as for LINQ and C#, not by default.
However, in the Person class you can override the ToString() event to do it for you.
public override string ToString()
{
return string.Format("p.Firstname={0} p.MI={1} p.LastName={2}", FirstName, MI, LastName);
}
And then you would just call it as follows:
string myString = p.ToString();
Which will give you the output you are looking for.
Upvotes: 1