using System.Collections.Specialized; using System.Linq; using System.Web.Routing; namespace LeafWeb.WebCms.Utility { public static class NameValueCollectionUtil { public static NameValueCollection GetNameValueCollection(this object obj, string prefix = "") { var nvs = new NameValueCollection(); prefix = string.IsNullOrEmpty(prefix) ? "" : prefix + "."; foreach (var pi in obj.GetType().GetProperties().Where(p => p.CanWrite)) { var value = pi.GetValue(obj, null); switch (value) { case null: case bool b when b == false: continue; default: nvs.Add(prefix + pi.Name, value.ToString()); break; } } return nvs; } public static RouteValueDictionary ToRouteValueDictionary(this NameValueCollection nvc) { var routeValues = new RouteValueDictionary(); foreach (var key in nvc.AllKeys) routeValues.Add(key, nvc[key]); return routeValues; } } }