2011-08-06 23 views
28

Tôi có đoạn mã sau:Nhận tất cả các giá trị của một NameValueCollection thành một chuỗi

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

Tôi đã cố gắng để chơi xung quanh với get:

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

Nhưng tất nhiên điều đó không làm việc .

Tôi cần một cái gì đó tương tự để có được tất cả các giá trị, nhưng tôi dường như không tìm thấy mã thích hợp để làm như vậy.

P.S: Tôi không muốn sử dụng vòng lặp foreach vì điều đó đánh bại mục đích của dòng mã đầu tiên.

Trả lời

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" 

Bạn cũng có thể tạo ra một phương pháp khuyến nông:

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

Cách sử dụng:

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

Ngoài ra bạn có thể dễ dàng chuyển đổi NameValueCollection để thuận tiện hơn Dictionary<string,string> vậy:

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

Cung cấp:

var d = c.ToDictionary(); 

Như tôi đã tìm thấy sử dụng Reflector, NameValueCollection.AllKeys nội bộ thực hiện một vòng lặp để thu thập tất cả các phím te, vì vậy nó có vẻ như c.Cast<string>() là một lợi thế hơn.

+0

chỉ là một bổ sung nhỏ, có thể trích dẫn được thêm vào từng giá trị? – Dementic

+0

@Dementic: Sure. Chỉ cần sử dụng 'c.Select (e => String.Format (" \ "{0} \" ", c [e]));' – abatishchev

+0

cảm ơn bạn, đây là một câu trả lời rất hay! – Dementic

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

Edit: Những câu trả lời khác có thể hoặc không thể là những gì bạn muốn. Chúng xuất hiện đơn giản hơn, nhưng kết quả có thể không phải là những gì bạn đang tìm kiếm trong mọi trường hợp, nhưng sau đó một lần nữa, chúng có thể là (số dặm của bạn có thể thay đổi).

Lưu ý rằng NameValueCollection không phải là ánh xạ 1: 1 như từ điển. Bạn có thể thêm nhiều giá trị cho cùng một khóa, đó là lý do tại sao một hàm như .GetValues(key) trả về một mảng chứ không phải một chuỗi.

Nếu bạn có một bộ sưu tập mà bạn đã thêm

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

Lấy collection["Alpha"] sản lượng "1,2". Đang truy xuất collection.GetValues("Alpha") sản lượng { "1", "2" }. Bây giờ, nó chỉ như vậy sẽ xảy ra rằng bạn đang sử dụng dấu phẩy để nối các giá trị của bạn với nhau thành một chuỗi duy nhất, vì vậy sự chênh lệch này bị ẩn. Tuy nhiên, nếu bạn đã được tham gia vào giá trị khác, chẳng hạn như một dấu chấm than, kết quả của các câu trả lời khác sẽ

"1,2!3" 

Và mã ở đây sẽ là

"1!2!3" 

Sử dụng đoạn mã mà thể hiện sự hành vi bạn thích.

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

Đây là cách tôi đã làm. Giải pháp đơn giản nhất, nhưng có lẽ không phải là giải pháp dễ đọc nhất trong mọi trường hợp. Điều này cũng có thể được thực hiện bằng cách sử dụng vòng lặp foreach và chỉ ghép nối cặp khóa: giá trị. – 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()); 

Bạn có thể thử một cái gì đó giống như ở trên.

7

Sau tạo chuỗi từ danh sách tham số URL.

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

tức

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

sẽ

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

Trong trường hợp bạn đã phân tích các chuỗi truy vấn với System.Web.HttpUtility.ParseQueryString (...) bạn chỉ có thể sử dụng ToString() và bạn không phải phát minh lại bánh xe.

Mặc dù kết quả là NameValueCollection, loại cơ bản là HttpValueCollection có ToString() ghi đè cần thiết để xây dựng lại chuỗi truy vấn.

0

Tôi đang sử dụng Azure DocumentDB như cơ chế khai thác gỗ của tôi, do đó viết một đối tượng năng động, nhưng bạn sẽ có được các ý chính ...

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

Tôi có một CustomException nơi tôi kiểm tra một ứng dụng của bộ mã phản hồi.

Ngoài ra, tôi lấy chuỗi truy vấn, dữ liệu biểu mẫu và mô hình để tôi có thể thấy các giá trị được chuyển trước và sau bộ mô hình.

Nếu cuộc gọi của nó và Ajax, tôi trả về một câu trả lời có định dạng Json. Nếu không, tôi sẽ trả lại một trang lỗi tùy chỉnh.

Các vấn đề liên quan