0

Having this data:

class User
{
    public string Name {get; set;}
    public string SurrName {get; set;}
}

class Book
{
    public int Id {get; set;}
    public string Title {get; set;}
}

var user = getSampleUser();
var book = getSampleBook();

I want to create string which will constains serialized object to &name=value.

var userContent = user.ToRequestContent(); // "&Name=Adam&Surrname=Smith";
var bookContent = book.ToRequestContent(); // "&Id=5&Title=7";

How can I do that?

D-Shih
  • 44,943
  • 6
  • 31
  • 51
dafie
  • 951
  • 7
  • 25
  • 4
    Possible duplicate of [How do I serialize an object into query-string format?](https://stackoverflow.com/questions/6848296/how-do-i-serialize-an-object-into-query-string-format) – wiero Oct 05 '18 at 09:36
  • If you have only few properties, you can just override ToString method and format string to your needs. – Renatas M. Oct 05 '18 at 09:38

2 Answers2

3

You can try to use linq with reflation to get Properties information and value.

I would write a extention method.

public static class ExtenstionArray
{
    public static string ToRequestContent<T>(this T model) {
        var list = model.GetType().GetProperties()
               .Select(x => new
               {
                   val = x.GetValue(model).ToString(),
                   name = x.Name
               })
               .Select(z => string.Join("=", z.name, z.val));

        return "&"+ string.Join("&", list);
    }
}

Then you can use like this.

User u = new User() { Name = "test", SurrName = "aa" };
Book b = new Book() { Id = 134, Title = "aass" };
Console.WriteLine( u.ToRequestContent());
Console.WriteLine( b.ToRequestContent());

c# online

Result

&Name=test&SurrName=aa
&Id=134&Title=aass
D-Shih
  • 44,943
  • 6
  • 31
  • 51
0

why not just:

class User
{
    public string Name {get; set;}
    public string SurrName {get; set;}
    public string ToRequestContent()
    {
         return "&Name="+Name+"&Surrname="+SurrName;
    }
}

class Book
{
    public int Id {get; set;}
    public string Title {get; set;}
    public string ToRequestContent()
    {
         return "&Id="+Id+"&Title="+Title;
    }
}
Itamar Kerbel
  • 2,508
  • 1
  • 22
  • 29
  • Careful - if the OP wants to generate a query string, you need to encode the property values as suggested in https://stackoverflow.com/a/6848707/558486 – Rui Jarimba Oct 05 '18 at 09:43