-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathObjectExtensions.cs
More file actions
85 lines (65 loc) · 2.92 KB
/
Copy pathObjectExtensions.cs
File metadata and controls
85 lines (65 loc) · 2.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using SW.PrimitiveTypes;
namespace SW.HttpExtensions
{
public static class ObjectExtensions
{
public static string ToQueryString(this object obj)
{
string[] props = obj.GetType().GetProperties()
.Where(property =>
{
if (property.GetValue(obj) == null)
return false;
bool isEnumerable = property.PropertyType.GetInterface(nameof(IEnumerable)) != null &&
property.PropertyType != typeof(string);
if (!isEnumerable)
return true;
IEnumerable tmp = ((IEnumerable)property.GetValue(obj).ConvertValueToType(property.PropertyType));
IEnumerable<string> enumerable = tmp.Cast<string>();
return enumerable.Any();
})
.Select(property =>
{
bool isEnumerable = property.PropertyType.GetInterface(nameof(IEnumerable)) != null &&
property.PropertyType != typeof(string);
if (isEnumerable)
{
IEnumerable tmp =
((IEnumerable)property.GetValue(obj).ConvertValueToType(property.PropertyType));
Type nested = property.PropertyType.GetElementType() ??
property.PropertyType.GetGenericArguments()[0];
int length = 0;
foreach (var val in tmp) ++length;
Array array = Array.CreateInstance(nested, length);
int counter = 0;
foreach (var val in tmp)
{
array.SetValue(val, counter);
++counter;
}
string q = string.Empty;
for (var i = 0; i < array.Length - 1; i++)
q += $"{property.Name}={array.GetValue(i)}&";
q += $"{property.Name}={array.GetValue(array.Length - 1)}";
return q;
}
else
{
var value = property.GetValue(obj);
if (value == null) return string.Empty;
else return $"{property.Name}={property.GetValue(obj)}";
}
})
.ToArray();
string queryString = string.Empty;
for (int i = 0; i < props.Count() - 1; i++)
queryString += props[i] + '&';
queryString += props[props.Length - 1];
return queryString;
}
}
}