简体   繁体   English

获取NameValueCollection的所有值到字符串

[英]Get all values of a NameValueCollection to a string

I have the following code: 我有以下代码:

string Keys = string.Join(",",FormValues.AllKeys);

I was trying to play around with the get: 我试图玩弄这个:

string Values = string.Join(",", FormValues.AllKeys.GetValue());

But of course that doesn't work. 但当然这不起作用。

I need something similar to get all the values, but I don't seem to find the appropriate code to do the same. 我需要类似的东西来获取所有值,但我似乎没有找到相同的代码来执行相同的操作。

PS: I do not want to use a foreach loop since that beats the purpose of the first line of code. PS:我不想使用foreach循环,因为这超出了第一行代码的目的。

var col = new NameValueCollection() { { "a", "b" }, { "1", "2" } }; // collection initializer

var values = col.Cast<string>().Select(e => col[e]); // b, 2

var str = String.Join(",", values );  // "b,2"

Also you can create an extension method: 您还可以创建一个扩展方法:

public static string Join(this NameValueCollection collection, Func<string,string> selector, string separator)
{
    return String.Join(separator, collection.Cast<string>().Select(e => selector(e)));
}

Usage: 用法:

var s = c.Join(e => String.Format("\"{0}\"", c[e]), ",");

Also you can easily convert NameValueCollection to more handy Dictionary<string,string> so: 您还可以轻松地将NameValueCollection转换为更方便的Dictionary<string,string>所以:

public static IDictionary<string,string> ToDictionary(this NameValueCollection col)
{
    return col.AllKeys.ToDictionary(x => x, x => col[x]);
}

Gives: 得到:

var d = c.ToDictionary();

As I found using Reflector, NameValueCollection.AllKeys internally performs a loop to gather all te keys, so it seems that c.Cast<string>() is more preferable. 正如我发现使用Reflector, NameValueCollection.AllKeys内部执行循环以收集所有te键,因此似乎更优选c.Cast<string>()

string values = string.Join(",", collection.AllKeys.Select(key => collection[key]));

Following creates a string from URL parameter list. 以下从URL参数列表创建一个字符串。

string.Join(", ", 
            Request.QueryString
                   .AllKeys
                   .Select(key => key + ": " + Request.QueryString[key])
      .ToArray())

ie

page.aspx?id=75&page=3&size=7&user=mamaci

would be 将会

id: 75, page: 3, size: 7, user: mamaci
string values = 
    string.Join(",", FormValues.AllKeys.SelectMany(key => FormValues.GetValues(key)));

Edit: The other answers may or may not be what you want. 编辑:其他答案可能是也可能不是你想要的。 They appear simpler, but the results might not be what you are looking for in all circumstances, but then again, they might be (your mileage may vary). 它们看起来更简单,但结果可能不是您在任何情况下都要寻找的结果,但是它们可能是(您的里程可能会有所不同)。

Note that a NameValueCollection is not a 1:1 mapping like a dictionary. 请注意, NameValueCollection不像字典那样是1:1映射。 You can add multiple values for the same key, which is why a function like .GetValues(key) returns an array, not a single string. 您可以为同一个键添加多个值,这就是.GetValues(key)类的函数返回数组而不是单个字符串的原因。

If you have a collection where you have added 如果您有一个已添加的集合

 collection.Add("Alpha", "1");
 collection.Add("Alpha", "2");
 collection.Add("Beta", "3");

Retrieving collection["Alpha"] yields "1,2" . 检索collection["Alpha"]产生"1,2" Retrieving collection.GetValues("Alpha") yields { "1", "2" } . 检索collection.GetValues("Alpha")产生{ "1", "2" } Now, it just so happens that you are using a comma to join your values together into a single string, so this disparity is hidden. 现在,恰好您正在使用逗号将您的值一起合并为一个字符串,因此隐藏了这种差异。 However, if you were joining on another value, such as an exclamation point, the results of the other answers would be 但是,如果您要加入其他值(例如感叹号),则其他答案的结果将是

"1,2!3"

And the code here would be 这里的代码就是

"1!2!3"

Use the snippet that demonstrates the behavior you prefer. 使用演示您喜欢的行为的代码段。

In cases where you have parsed the query string with System.Web.HttpUtility.ParseQueryString(...) you can just use ToString() and you don't have to re-invent the wheel. 如果您使用System.Web.HttpUtility.ParseQueryString(...)解析了查询字符串,则只需使用ToString(),就不必重新发明轮子。

Even though result is NameValueCollection, the underlying type is HttpValueCollection which has the necessary ToString() override to build back a query string. 尽管结果是NameValueCollection,但底层类型是HttpValueCollection,它具有必要的ToString()覆盖以构建查询字符串。

I'm using Azure DocumentDB as my logging mechanism, hence writing a dynamic object, but you get the gist... 我使用Azure DocumentDB作为我的日志记录机制,因此编写了一个动态对象,但是你得到了主旨......

public class LogErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        int responseCode = new int();

        // Has the exception been handled.  Also, are custom errors enabled
        if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
            return;

        // Check if custom exception, if so get response code
        if (filterContext.Exception is CustomException)
            responseCode = (int)((CustomException)filterContext.Exception).Code;

        // Log exception
        string id = Logging.Write(LogType.Error, new
        {
            ResponseCode = responseCode,
            Exception = new
            {
                Message = filterContext.Exception.Message,
                Data = filterContext.Exception.Data,
                Source = filterContext.Exception.Source,
                StackTrace = filterContext.Exception.StackTrace,
                InnerException = filterContext.Exception.InnerException != null ? new
                {
                    Message = filterContext.Exception.InnerException.Message,
                    Data = filterContext.Exception.InnerException.Data,
                    Source = filterContext.Exception.InnerException.Source,
                    StackTrace = filterContext.Exception.InnerException.StackTrace
                } : null
            },
            Context = filterContext.Controller != null ? new
            { 
                RouteData = filterContext.Controller.ControllerContext.RouteData,
                QueryString = filterContext.Controller.ControllerContext.HttpContext.Request.Url.Query,
                FormParams = filterContext.Controller.ControllerContext.HttpContext.Request.Form != null ? string.Join(";#", filterContext.Controller.ControllerContext.HttpContext.Request.Form.AllKeys.Select(key => key + ":" + filterContext.Controller.ControllerContext.HttpContext.Request.Form[key])) : string.Empty,
                Model = (filterContext.Controller is Controller) ? ((Controller)filterContext.Controller).ModelState : null,
                ViewBag = filterContext.Controller.ViewBag,
                ViewData = filterContext.Controller.ViewData
            } : null,
            ActionResult = filterContext.Result != null ? filterContext.Result : null,
            Referrer = filterContext.HttpContext.Request.UrlReferrer != null ? filterContext.HttpContext.Request.UrlReferrer : null
        }).Result;

        // Mark exception as handled and return
        filterContext.ExceptionHandled = true;

        // Test for Ajax call
        if (IsAjax(filterContext))
        {
            // Construct appropriate Json response
            filterContext.Result = new JsonResult()
            {
                Data = new
                {
                    code = responseCode,
                    id = id,
                    message = filterContext.Exception.Message
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

        }
        else
        {
            var result = new ViewResult();
            result.ViewName = "_CustomError";
            result.ViewBag.CorrelationId = id;
            filterContext.Result = result;
        }
    }

    /// <summary>
    /// Determine if the request is from an Ajax call
    /// </summary>
    /// <param name="filterContext">The request context</param>
    /// <returns>True or false for an Ajax call</returns>
    private bool IsAjax(ExceptionContext filterContext)
    {
        return filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
    }
}

I have a CustomException where I check for a application-set response code. 我有一个CustomException ,我检查应用程序集响应代码。

Additionally, I take the querystring, form data, and the model so that I can see the values passed before and after the model binder. 另外,我使用查询字符串,表单数据和模型,以便我可以看到模型绑定器之前和之后传递的值。

If its and Ajax call, I return a Json-formatted response. 如果它和Ajax调用,我返回一个Json格式的响应。 Otherwise, I return a custom error page. 否则,我返回一个自定义错误页面。

List<string> values = new List<string>();
values.AddRange(all.AllKeys.SelectMany(all.GetValues).Where(getValues => getValues != null));
string Values = string.Join(",", values.ToArray());

You can try something like the above. 你可以尝试类似上面的东西。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM