Created
September 30, 2016 09:52
-
-
Save i-sync/bb30e13439f05b47f1a28a496e0bc04b to your computer and use it in GitHub Desktop.
String Format With Name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string FormatWith(this string format, object source) | |
{ | |
return FormatWith(format, null, source); | |
} | |
public static string FormatWith(this string format, IFormatProvider provider, object source) | |
{ | |
if (format == null) | |
throw new ArgumentNullException("format"); | |
Regex r = new Regex(@"(?<start>\{)+(?<property>[\w\.\[\]]+)(?<format>:[^}]+)?(?<end>\})+", | |
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); | |
List<object> values = new List<object>(); | |
string rewrittenFormat = r.Replace(format, delegate (Match m) | |
{ | |
Group startGroup = m.Groups["start"]; | |
Group propertyGroup = m.Groups["property"]; | |
Group formatGroup = m.Groups["format"]; | |
Group endGroup = m.Groups["end"]; | |
values.Add((propertyGroup.Value == "0") | |
? source | |
: System.Web.UI.DataBinder.Eval(source, propertyGroup.Value)); | |
return new string('{', startGroup.Captures.Count) + (values.Count - 1) + formatGroup.Value | |
+ new string('}', endGroup.Captures.Count); | |
}); | |
return string.Format(provider, rewrittenFormat, values.ToArray()); | |
} | |
//use | |
string result = "{Url}?roomnum={RoomNum}&productnum={ProductNum}&giftnum={GiftNum}&hotelcode={HotelCode}&checkin={CheckIn}&checkout={CheckOut}&adults={Adults}&children={Children}&roomtype={RoomType}&roomid={RoomId}&ratecode={RateCode}&servicedata={ServiceData}&upgradespecified={UpgradeSpecified}&discountcode={DiscountCode}&groupcode={GroupCode}&promocode={PromoCode}&roomflag={RoomFlag}&share=true&productcode={ProductCode}&traveldate={TravelDate}&gradecode={GradeCode}&agebands={AgeBands}&hoteloption={HotelOption}&hotelid={HotelId}&hotelname={HotelName}&hoteladdress={HotelAddress}&productflag={ProductFlag}"; | |
var temp = new | |
{ | |
Url = string.Format("{0}://{1}/{2}", HostResolver.RequestScheme,Request.Url.Host,CookieUtil.GetWebsiteLanguage()), | |
RoomNum, | |
ProductNum, | |
GiftNum, | |
//room | |
HotelCode, | |
CheckIn, | |
CheckOut, | |
Adults, | |
Children, | |
RoomType, | |
RoomId, | |
RateCode, | |
ServiceData, | |
UpgradeSpecified, | |
DiscountCode, | |
GroupCode, | |
PromoCode, | |
RoomFlag, | |
//product | |
ProductCode, | |
TravelDate, | |
GradeCode, | |
AgeBands, | |
HotelOption, | |
HotelId, | |
HotelName, | |
HotelAddress, | |
ProductFlag | |
//gift | |
}; | |
result = result.FormatWith(temp); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment