35

私は次のコードを持っています:

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

私はgetで遊んでみました:

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

しかしもちろん、それは機能しません。

すべての値を取得するために似たようなものが必要ですが、同じことを行うための適切なコードが見つからないようです。

foreachPS:ループはコードの最初の行の目的に反するため、ループを使用したくありません。

4

7 に答える 7

41
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"

また、拡張メソッドを作成することもできます。

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

使用法:

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

NameValueCollectionまた、より便利なものに簡単に変換できるDictionary<string,string>ので、次のようになります。

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

与える:

var d = c.ToDictionary();

Reflectorを使用して見つけたように、NameValueCollection.AllKeys内部でループを実行してすべてのteキーを収集するため、c.Cast<string>()より望ましいようです。

于 2011-08-06T13:44:40.013 に答える
28
string values = string.Join(",", collection.AllKeys.Select(key => collection[key]));
于 2011-08-06T13:45:45.117 に答える
10

以下は、URLパラメータリストから文字列を作成します。

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

すなわち

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

だろう

id: 75, page: 3, size: 7, user: mamaci
于 2013-05-08T09:34:38.987 に答える
9
string values = 
    string.Join(",", FormValues.AllKeys.SelectMany(key => FormValues.GetValues(key)));

編集:他の答えはあなたが望むものであるかもしれないし、そうでないかもしれません。それらはより単純に見えますが、結果はすべての状況であなたが探しているものではないかもしれません、しかしそれでもまた、それらはそうかもしれません(あなたのマイレージは変わるかもしれません)。

NameValueCollectionaは辞書のような1:1マッピングではないことに注意してください。同じキーに複数の値を追加できるため、のような関数.GetValues(key)は単一の文字列ではなく配列を返します。

追加したコレクションがある場合

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

collection["Alpha"]利回りの取得"1,2"collection.GetValues("Alpha")利回りの取得{ "1", "2" }。さて、たまたまコンマを使用して値を1つの文字列に結合しているため、この不一致は隠されています。ただし、感嘆符などの別の値に参加している場合、他の回答の結果は次のようになります。

"1,2!3"

そして、ここのコードは

"1!2!3"

好みの動作を示すスニペットを使用してください。

于 2011-08-06T13:45:36.770 に答える
0

System.Web.HttpUtility.ParseQueryString(...)を使用してクエリ文字列を解析した場合は、ToString()を使用するだけで、車輪の再発明を行う必要はありません。

結果はNameValueCollectionですが、基になる型はHttpValueCollectionであり、クエリ文字列を再構築するために必要なToString()オーバーライドがあります。

于 2014-05-02T19:15:39.523 に答える
0

ロギングメカニズムとしてAzureDocumentDBを使用しているため、動的オブジェクトを記述していますが、要点はわかります...

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";
    }
}

アプリケーションセットの応答コードをチェックするCustomExceptionがあります。

さらに、クエリ文字列、フォームデータ、およびモデルを取得して、モデルバインダーの前後に渡された値を確認できるようにします。

そのとAjaxが呼び出された場合、Json形式の応答を返します。それ以外の場合は、カスタムエラーページを返します。

于 2015-03-31T20:34:47.083 に答える
-1
List<string> values = new List<string>();
values.AddRange(all.AllKeys.SelectMany(all.GetValues).Where(getValues => getValues != null));
string Values = string.Join(",", values.ToArray());

上記のようなものを試すことができます。

于 2011-08-06T13:54:11.470 に答える