[英]Dynamically constructing a GET query with optional parameters in C#
I have a class that contains all the properties of a query I'm constructing could possibly have (most of which are optional)我有一个 class 包含我正在构建的查询可能具有的所有属性(其中大部分是可选的)
For example:例如:
public class QueryClass
{
public string Offset {get; set;}
public string Limit {get; set;}
public string Sort {get; set;}
}
Then in a BuildQuery()
method I am constructing the query by doing this:然后在
BuildQuery()
方法中,我通过执行以下操作构建查询:
private string BuildQuery(QueryClass query)
{
var queryDictionary = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(query.Offset)
{
queryDictionary.Add("offset", query.Offset);
}
if (!string.IsNullOrEmpty(query.Limit)
{
queryDictionary.Add("limit", query.Limit);
}
if (!string.IsNullOrEmpty(query.Sort)
{
queryDictionary.Add("sort", query.Sort);
}
var content = new FormUrlEncodedContent(queryDictionary);
return content.ReadAsStringAsync().Result;
}
This works, but the issue is my actual QueryClass is significantly larger than this, there's got to be a better way to do this than to have a ton of IF statements for every optional property but I haven't been able to come up with a more elegant solution.这行得通,但问题是我的实际 QueryClass 比这大得多,必须有更好的方法来做到这一点,而不是为每个可选属性设置大量 IF 语句,但我无法想出一个更优雅的解决方案。 I also don't care for adding the keys in the dictionary in this way, I probably need a new approach for how I structure the
QueryClass
.我也不关心以这种方式在字典中添加键,我可能需要一种新方法来构建
QueryClass
。
If you don't mind taking the reflection hit, just project, filter nulls , then send to ToDictionary
如果您不介意反射命中,只需投影,过滤nulls ,然后发送到
ToDictionary
Note : The assumptions here are, all the property names are your keys, and all the properties are convertible to string注意:这里的假设是,所有属性名都是你的键,所有属性都可以转换为字符串
var queryClass = new QueryClass()
{
Limit = "asdf",
Sort = "Bob"
};
var results = queryClass
.GetType()
.GetProperties()
.Select(x => (Value: x.GetValue(queryClass) as string, x.Name))
.Where(x => !string.IsNullOrWhiteSpace(x.Value))
.ToDictionary(
x => x.Name.ToLower(),
x => x.Value);
foreach (var (key, value) in results)
Console.WriteLine($"{key} : {value}");
Output Output
limit : asdf
sort : Bob
Add pepper and salt to taste加入胡椒和盐调味
Or as an extension method或作为扩展方法
public static IDictionary<string, string> ConvertToDictionary<T>(this T source)
=> typeof(T).GetProperties()
.Select(x => (Value: x.GetValue(source) as string, x.Name))
.Where(x => !string.IsNullOrWhiteSpace(x.Value))
.ToDictionary(
x => x.Name.ToLower(),
x => x.Value!);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.