2011-08-06 9 views
28

私は、次のコードを持っている:文字列にNameValueCollectionのすべての値を取得します

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

私が手で遊んでしようとしていた。

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

しかし、もちろん動作しません。 。

私はすべての値を取得するために同様のものが必要ですが、私は同じことを行うための適切なコードを見つけるように見えません。

P.S:foreachループを使用したくないのは、最初のコード行の目的に反します。

答えて

34
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>そうに変換することができます

が与える:

var d = c.ToDictionary(); 

をIリフレクタ、NameValueCollection.AllKeysを使用して見られるような内部のすべてのTEキーを収集するループを実行するので、c.Cast<string>()がより好ましいと思われます。

+0

ちょっと追加して、各値に引用符を追加できますか? – Dementic

+0

@Dementic:はい。 'c.Select(e => String.Format(" \ "{0} \" "、c [e])); ' – abatishchev

+0

ありがとう、本当に素敵な答えでした! – Dementic

7
string values = 
    string.Join(",", FormValues.AllKeys.SelectMany(key => FormValues.GetValues(key))); 

編集:他の回答は、またはあなたが望むものであってもなくてもよいです。彼らはよりシンプルに見えますが、結果はすべての状況であなたが探しているものではないかもしれませんが、再び(あなたの走行距離は変わるかもしれません)かもしれません。

NameValueCollectionは、辞書のように1:1マッピングではありません。同じキーに複数の値を追加することができます。その理由は、.GetValues(key)のような関数が配列を返します。単一の文字列ではありません。

あなたはcollection["Alpha"]利回り"1,2"を取得

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

を追加したコレクションを持っている場合。 collection.GetValues("Alpha")を検索すると、{ "1", "2" }が得られます。これで、コンマを使用して値を1つの文字列に結合するので、この格差は隠されます。あなたは、このような感嘆符として、別の値に参加した場合は、他の回答の結果は

"1,2!3" 

そしてここでコードが

"1!2!3" 

実証スニペットを使用してくださいだろうだろうあなたが好む行動。

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

これは私がそれをした方法です。最も単純なソリューションですが、すべてのインスタンスで最も読みやすいわけではありません。これは、foreachループを使用し、key:valueのペアを連結することによっても達成できます。 – Blairg23

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

あなたは上記のような何かを試すことができます。

7

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

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

すなわち

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

はあなたがちょうど使用することができますSystem.Web.HttpUtility.ParseQueryString(...)でのクエリ文字列を解析されている場合には

id: 75, page: 3, size: 7, user: mamaci 
0

だろうToString()とホイールを再発明する必要はありません。

結果がNameValueCollectionであっても、基になる型は、クエリ文字列を構築するために必要なToString()オーバーライドを持つHttpValueCollectionです。私は、したがって、動的オブジェクトを書いていますが、要点を取得し、私のロギングメカニズムとしてアズールDocumentDBを使用してい

0

...

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形式の応答を返します。それ以外の場合は、カスタムエラーページを返します。

関連する問題