我有一个类,其中包含我正在构造的查询可能具有的所有属性(其中大部分是可选的)
例如:
public class QueryClass
{
public string Offset {get; set;}
public string Limit {get; set;}
public string Sort {get; set;}
}
然后在
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;
}
这可行,但问题是我的实际 QueryClass 显着比这大,必须有更好的方法来做到这一点,而不是为每个可选属性使用大量 IF 语句,但我还没有能够做到提出一个更优雅的解决方案。我也不喜欢以这种方式在字典中添加键,我可能需要一种新的方法来构建
QueryClass
。
如果你不介意受到反射命中,只需投影,过滤nulls,然后发送到
ToDictionary
注意:这里的假设是,所有属性名称都是你的键,并且所有属性都可以转换为字符串
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}");
输出
limit : asdf
sort : Bob
加胡椒粉和盐调味
或者作为扩展方法
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!);