This repository has been archived by the owner on Nov 20, 2018. It is now read-only.
/
QueryBuilder.cs
81 lines (68 loc) · 2.37 KB
/
QueryBuilder.cs
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.Encodings.Web;
namespace Microsoft.AspNetCore.Http.Extensions
{
// The IEnumerable interface is required for the collection initialization syntax: new QueryBuilder() { { "key", "value" } };
public class QueryBuilder : IEnumerable<KeyValuePair<string, string>>
{
private IList<KeyValuePair<string, string>> _params;
public QueryBuilder()
{
_params = new List<KeyValuePair<string, string>>();
}
public QueryBuilder(IEnumerable<KeyValuePair<string, string>> parameters)
{
_params = new List<KeyValuePair<string, string>>(parameters);
}
public void Add(string key, IEnumerable<string> values)
{
foreach (var value in values)
{
_params.Add(new KeyValuePair<string, string>(key, value));
}
}
public void Add(string key, string value)
{
_params.Add(new KeyValuePair<string, string>(key, value));
}
public override string ToString()
{
var builder = new StringBuilder();
bool first = true;
for (int i = 0; i < _params.Count; i++)
{
var pair = _params[i];
builder.Append(first ? "?" : "&");
first = false;
builder.Append(UrlEncoder.Default.Encode(pair.Key));
builder.Append("=");
builder.Append(UrlEncoder.Default.Encode(pair.Value));
}
return builder.ToString();
}
public QueryString ToQueryString()
{
return new QueryString(ToString());
}
public override int GetHashCode()
{
return ToQueryString().GetHashCode();
}
public override bool Equals(object obj)
{
return ToQueryString().Equals(obj);
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return _params.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _params.GetEnumerator();
}
}
}