I need to serialise an object model containing arrays into a query string, I have the following code:
public static string ToQueryString(this object query)
{
var result = new List<string>();
var properties = query.GetType().GetProperties().Where(p => p.GetValue(query, null) != null && p.GetValue(query, null).ToString() != "0");
foreach (var p in properties)
{
var value = p.GetValue(query, null);
var collection = value as ICollection;
if (collection != null)
{
result.AddRange(from object o in collection select string.Format("{0}={1}", p.Name, HttpUtility.UrlEncode(o.ToString())));
}
else
{
result.Add($"{p.Name}={HttpUtility.UrlEncode(value.ToString())}");
}
}
return string.Join("&", result.ToArray());
}
and the following example model:
var model = new exampleModel()
{
OrderBy = "name",
OrderByDesc = true,
PersonName= "John",
Languages = new string[] { "French", "English", "Spanish" }
};
When the model is serialized the querystring is converted like this:
"OrderBy=name&OrderByDesc=true&PersonName=John&Languages=French&Languages=English&Languages=Spanish"
As you can see this is not desirable as the property "Languages" is repeated in the query string for each value in the collection. Does anyone know how can I manage to get the query string such as:
"OrderBy=name&OrderByDesc=true&PersonName=John&Languages=French,English,Spanish"
[{ }]button at the top of the editor.