简体   繁体   English

如何存储可空值并遍历它们?

[英]How Do I Store Nullable values and Iterate Through Them?

Thanks for taking a moment.感谢您抽出一点时间。 I have a url .我有一个网址。 I'm trying to build the querystring parameters from these nullable input parameters you see below.我正在尝试从您在下面看到的这些可为空的输入参数构建查询字符串参数。 I'm thinking what I need to do is store the nullable parameters into some type of generic list and then if the given value of the parameter is not null, append it to the url.我在想我需要做的是将可为空的参数存储到某种类型的通用列表中,然后如果参数的给定值不为空,则将其附加到 url。 So for example, If they supply the string?例如,如果他们提供字符串? state a value of 'OH' my url would look like ( http://www.thiscoolsiteJas.com/api/v1/moratorium?state=OH ).声明'OH'的值,我的 url 看起来像 ( http://www.thiscoolsiteJas.com/api/v1/moratorium?state=OH )。 How do I do this ?我该怎么做呢 ? Any advice or direction would be greatly appreciated.任何建议或方向将不胜感激。 - Jason - 杰森

 public  GetMoratoriums(string? state, int? system, DateTime? inEffectOn, bool? expired, int? reason) {
       //How do I build this with parameters  using the input parameters??
        string url = http://www.thiscoolsiteJas.com/api/v1/moratorium?";

} }

Something like this?像这样的东西?

var queryStrings = new List<string>();

if (state.HasValue) { queryStrings.Add($"state={state.Value}"); }
if (system.HasValue) { queryStrings.Add($"system={system.Value}"); }
if (inEffectOn.HasValue) { queryStrings.Add($"inEffectOn={inEffectOn.Value}"); }
if (expired.HasValue) { queryStrings.Add($"expired={expired.Value}"); }
if (reason.HasValue) { queryStrings.Add($"reason={reason.Value}"); }

var result = @"http://www.thiscoolsiteJas.com/api/v1/moratorium";
if (queryStrings.Any()) { result += $"?{String.Join("&", queryStrings)}"; }
return result;

I'm sure there is a better way to do it but this is how I would handle it.我确信有更好的方法来做到这一点,但这就是我的处理方式。

string url = http://www.thiscoolsiteJas.com/api/v1/moratorium?";

var queryStringParams = new List<KeyValuePair<string, string>>();

if (!string.IsNullOrEmpty(state))
   {
       queryStringParams.Add("state",state);
   }
etc...

var newUrl = new Uri(QueryHelpers.AddQueryString(url, queryStringParams));

Object oriented approach ;).面向对象的方法;)。

public class Parameter
{
    private readonly string _name;

    private readonly object _value;

    public Parameter(string name, object value)
    {
        _name = name;
        _value = value;
    }

    public string ForQuery()
    {
        return _value == null ? null : $"{_name}={_value}";
    }
}

Usage用法

string? state = "new_state";
int? system = 1;
DateTime? inEffectOn = default;
bool? expired = default;

var parameters = new[]
{
    new QueryParameter("state", state),
    new QueryParameter("system", system),
    new QueryParameter("inEffectOn", inEffectOn),
    new QueryParameter("expired", expired),
};

var queryParameters = parameters.Select(p => p.ForQuery()).Where(p => p != null);
var query = string.Join("&", queryParameters);

For example instead of passing long list of parameters you can pass a collection of value of type QueryParameter and build query.例如,您可以传递QueryParameter类型的值集合并构建查询,而不是传递长参数列表。

With extension method带扩展方式

public static string AppendTo(this IEnumerable<QueryParameter> parameters, string baseUrl) 
{
    return parameters
        .Select(p => p.ForQuery())
        .Where(p => p != null)
        .Aggregate(
            new StringBuilder(baseUrl),
            (builder, p) => builder.Append(p).Append("&"),
            (builder) => 
            {
                if (builder.Length > 0)
                {
                    builder.Insert(0, "?");
                    builder.Length -= 1; // remove last "&"
                }
            })
        .ToString();
}

Usage用法

var parameters = new[]
{
    new QueryParameter("state", "new"),
    new QueryParameter("system", null),
    new QueryParameter("inEffectOn", null),
    new QueryParameter("expired", false),
};

var url = parameters.AppendTo("http://www.thiscoolsiteJas.com/api/v1/moratorium");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何动态遍历嵌套的JSON并更新所有浮动类型的值 - How do i dynamically iterate through a nested JSON and update all the values that are floating type 如何使用可为空的值进行“一击”Linq查询? - How can I do a “one hit” Linq query with nullable values? 如何将 object 类型的值存储在数组中并调用它们(C#)? - How do I store the values of an object type in an array and call them (C#)? 是否可以创建一个字典,其中的值可以具有多种数据类型? (另外我如何遍历一个数组作为我的值之一) - Is it possible to create a dictionary in which values can have multiple data types? (Also how do I iterate through an array as one of my values) 如何冻结集合以便可以迭代它? - How do I freeze a collection so that I can iterate through it? 如何遍历Crystal Reports中的一组记录 - how do I Iterate through a group of records in Crystal Reports 如何遍历表以输入数据 - How do I iterate through a table to enter data 如何在GroupBox中迭代10个TextBox? - How do I iterate through 10 TextBox's in a GroupBox? C#如何遍历注册表? - C# How do i iterate through the registry? 如何在c#中迭代内部属性 - how do I iterate through internal properties in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM