分割驼峰
这是所有的asp.net c#。
我有一个枚举
public enum ControlSelectionType { NotApplicable = 1, SingleSelectRadioButtons = 2, SingleSelectDropDownList = 3, MultiSelectCheckBox = 4, MultiSelectListBox = 5 }
这个数值存储在我的数据库中。 我在一个数据网格中显示这个值。
<asp:boundcolumn datafield="ControlSelectionTypeId" headertext="Control Type"></asp:boundcolumn>
ID对于用户来说意味着什么,所以我已经用下面的方法将绑定列更改为模板列。
<asp:TemplateColumn> <ItemTemplate> <%# Enum.Parse(typeof(ControlSelectionType), DataBinder.Eval(Container.DataItem, "ControlSelectionTypeId").ToString()).ToString()%> </ItemTemplate> </asp:TemplateColumn>
这样会好很多…但是,如果有一个简单的函数,我可以放在Enum中,通过Camel case来分割它,以便在datagrid中很好地包装这些单词。
注意:我完全意识到有更好的方法来做这一切。 这个屏幕纯粹是在内部使用,我只是想要一个快速的黑客来显示它好一点。
确实,正则expression式/replace是其他答案中描述的方法,但是如果您想要转向不同的方向,这也可能对您有用
using System.ComponentModel; using System.Reflection;
…
public static string GetDescription(System.Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) return attributes[0].Description; else return value.ToString(); }
这将允许你定义你的枚举
public enum ControlSelectionType { [Description("Not Applicable")] NotApplicable = 1, [Description("Single Select Radio Buttons")] SingleSelectRadioButtons = 2, [Description("Completely Different Display Text")] SingleSelectDropDownList = 3, }
取自
http://www.codeguru.com/forum/archive/index.php/t-412868.html
我用了:
public static string SplitCamelCase(string input) { return System.Text.RegularExpressions.Regex.Replace(input, "([AZ])", " $1", System.Text.RegularExpressions.RegexOptions.Compiled).Trim(); }
取自http://weblogs.asp.net/jgalloway/archive/2005/09/27/426087.aspx
如果C#3.0是一个选项,你可以使用下面的一行来完成这个工作:
Regex.Matches(YOUR_ENUM_VALUE_NAME, "[AZ][az]+").OfType<Match>().Select(match => match.Value).Aggregate((acc, b) => acc + " " + b).TrimStart(' ');
这个正则expression式(^[az]+|[AZ]+(?![az])|[AZ][az]+)
可以用来从camelCase或者PascalCase名字中提取所有单词。 它也适用于名称内任何地方的缩写。
-
MyHTTPServer
将包含3个匹配:My
,HTTP
,Server
-
myNewXMLFile
将包含4个匹配项:my
,New
,XML
,File
然后,您可以使用string.Join
将它们join到单个string中。
string name = "myNewUIControl"; string[] words = Regex.Matches(name, "(^[az]+|[AZ]+(?![az])|[AZ][az]+)") .OfType<Match>() .Select(m => m.Value) .ToArray(); string result = string.Join(" ", words);
下面是一个处理数字和多个大写字符的扩展方法,也允许在最后一个string中使用大写字母的特定首字母缩略词:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; using System.Text.RegularExpressions; using System.Web.Configuration; namespace System { /// <summary> /// Extension methods for the string data type /// </summary> public static class ConventionBasedFormattingExtensions { /// <summary> /// Turn CamelCaseText into Camel Case Text. /// </summary> /// <param name="input"></param> /// <returns></returns> /// <remarks>Use AppSettings["SplitCamelCase_AllCapsWords"] to specify a comma-delimited list of words that should be ALL CAPS after split</remarks> /// <example> /// wordWordIDWord1WordWORDWord32Word2 /// Word Word ID Word 1 Word WORD Word 32 Word 2 /// /// wordWordIDWord1WordWORDWord32WordID2ID /// Word Word ID Word 1 Word WORD Word 32 Word ID 2 ID /// /// WordWordIDWord1WordWORDWord32Word2Aa /// Word Word ID Word 1 Word WORD Word 32 Word 2 Aa /// /// wordWordIDWord1WordWORDWord32Word2A /// Word Word ID Word 1 Word WORD Word 32 Word 2 A /// </example> public static string SplitCamelCase(this string input) { if (input == null) return null; if (string.IsNullOrWhiteSpace(input)) return ""; var separated = input; separated = SplitCamelCaseRegex.Replace(separated, @" $1").Trim(); //Set ALL CAPS words if (_SplitCamelCase_AllCapsWords.Any()) foreach (var word in _SplitCamelCase_AllCapsWords) separated = SplitCamelCase_AllCapsWords_Regexes[word].Replace(separated, word.ToUpper()); //Capitalize first letter var firstChar = separated.First(); //NullOrWhiteSpace handled earlier if (char.IsLower(firstChar)) separated = char.ToUpper(firstChar) + separated.Substring(1); return separated; } private static readonly Regex SplitCamelCaseRegex = new Regex(@" ( (?<=[az])[A-Z0-9] (?# lower-to-other boundaries ) | (?<=[0-9])[a-zA-Z] (?# number-to-other boundaries ) | (?<=[AZ])[0-9] (?# cap-to-number boundaries; handles a specific issue with the next condition ) | (?<=[AZ])[AZ](?=[az]) (?# handles longer strings of caps like ID or CMS by splitting off the last capital ) )" , RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace ); private static readonly string[] _SplitCamelCase_AllCapsWords = (WebConfigurationManager.AppSettings["SplitCamelCase_AllCapsWords"] ?? "") .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(a => a.ToLowerInvariant().Trim()) .ToArray() ; private static Dictionary<string, Regex> _SplitCamelCase_AllCapsWords_Regexes; private static Dictionary<string, Regex> SplitCamelCase_AllCapsWords_Regexes { get { if (_SplitCamelCase_AllCapsWords_Regexes == null) { _SplitCamelCase_AllCapsWords_Regexes = new Dictionary<string,Regex>(); foreach(var word in _SplitCamelCase_AllCapsWords) _SplitCamelCase_AllCapsWords_Regexes.Add(word, new Regex(@"\b" + word + @"\b", RegexOptions.Compiled | RegexOptions.IgnoreCase)); } return _SplitCamelCase_AllCapsWords_Regexes; } } } }
Tillito的答案不处理已经包含空格的string,或者首字母缩写词。 这解决了它:
public static string SplitCamelCase(string input) { return Regex.Replace(input, "(?<=[az])([AZ])", " $1", RegexOptions.Compiled); }
public enum ControlSelectionType { NotApplicable = 1, SingleSelectRadioButtons = 2, SingleSelectDropDownList = 3, MultiSelectCheckBox = 4, MultiSelectListBox = 5 } public class NameValue { public string Name { get; set; } public object Value { get; set; } } public static List<NameValue> EnumToList<T>(bool camelcase) { var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>()); var array2 = Enum.GetNames(typeof(T)).ToArray<string>(); List<NameValue> lst = null; for (int i = 0; i < array.Length; i++) { if (lst == null) lst = new List<NameValue>(); string name = ""; if (camelcase) { name = array2[i].CamelCaseFriendly(); } else name = array2[i]; T value = array[i]; lst.Add(new NameValue { Name = name, Value = value }); } return lst; } public static string CamelCaseFriendly(this string pascalCaseString) { Regex r = new Regex("(?<=[az])(?<x>[AZ])|(?<=.)(?<x>[AZ])(?=[az])"); return r.Replace(pascalCaseString, " ${x}"); } //In your form protected void Button1_Click1(object sender, EventArgs e) { DropDownList1.DataSource = GeneralClass.EnumToList<ControlSelectionType >(true); ; DropDownList1.DataTextField = "Name"; DropDownList1.DataValueField = "Value"; DropDownList1.DataBind(); }
Eoin Campbell的解决scheme工作良好,除非您有Web服务。
由于说明属性不可序列化,因此您需要执行以下操作。
[DataContract] public enum ControlSelectionType { [EnumMember(Value = "Not Applicable")] NotApplicable = 1, [EnumMember(Value = "Single Select Radio Buttons")] SingleSelectRadioButtons = 2, [EnumMember(Value = "Completely Different Display Text")] SingleSelectDropDownList = 3, } public static string GetDescriptionFromEnumValue(Enum value) { EnumMemberAttribute attribute = value.GetType() .GetField(value.ToString()) .GetCustomAttributes(typeof(EnumMemberAttribute), false) .SingleOrDefault() as EnumMemberAttribute; return attribute == null ? value.ToString() : attribute.Value; }
您可以使用C#扩展方法
public static string SpacesFromCamel(this string value) { if (value.Length > 0) { var result = new List<char>(); char[] array = value.ToCharArray(); foreach (var item in array) { if (char.IsUpper(item)) { result.Add(' '); } result.Add(item); } return new string(result.ToArray()); } return value; }
那么你可以使用它
var result = "TestString".SpacesFromCamel();
结果会是
testingstring
使用LINQ:
var chars = ControlSelectionType.NotApplicable.ToString().SelectMany((x, i) => i > 0 && char.IsUpper(x) ? new char[] { ' ', x } : new char[] { x }); Console.WriteLine(new string(chars.ToArray()));
如果你不喜欢使用正则expression式 – 试试这个:
public static string SeperateByCamelCase(this string text, char splitChar = ' ') { var output = new StringBuilder(); for (int i = 0; i < text.Length; i++) { var c = text[i]; //if not the first and the char is upper if (i > 0 && char.IsUpper(c)) { var wasLastLower = char.IsLower(text[i - 1]); if (i + 1 < text.Length) //is there a next { var isNextUpper = char.IsUpper(text[i + 1]); if (!isNextUpper) //if next is not upper (start of a word). { output.Append(splitChar); } else if (wasLastLower) //last was lower but i'm upper and my next is an upper (start of an achromin). 'abcdHTTP' 'abcd HTTP' { output.Append(splitChar); } } else { //last letter - if its upper and the last letter was lower 'abcd' to 'abcd A' if (wasLastLower) { output.Append(splitChar); } } } output.Append(c); } return output.ToString(); }
通过这些testing,它不喜欢数字,但我不需要它。
[TestMethod()] public void ToCamelCaseTest() { var testData = new string[] { "AAACamel", "AAA", "SplitThisByCamel", "AnA", "doesnothing", "a", "A", "aasdasdAAA" }; var expectedData = new string[] { "AAA Camel", "AAA", "Split This By Camel", "An A", "doesnothing", "a", "A", "aasdasd AAA" }; for (int i = 0; i < testData.Length; i++) { var actual = testData[i].SeperateByCamelCase(); var expected = expectedData[i]; Assert.AreEqual(actual, expected); } }
我也有一个enum
,我不得不分开。 在我的情况下,这个方法解决了问题 –
string SeparateCamelCase(string str) { for (int i = 1; i < str.Length; i++) { if (char.IsUpper(str[i])) { str = str.Insert(i, " "); i++; } } return str; }
- 我如何才能找出哪些服务器主机LDAP在我的Windows域?
- 在ASP.NET应用程序之间传递会话数据
- WebClient.DownloadString()返回具有特殊字符的string
- ASP.Netvalidation摘要导致页面跳转到顶部
- ASP.NET中的多选下拉列表
- ASP.NET MVC:数据input后修剪string的最佳方法。 我应该创build一个自定义模型绑定
- 如何使用ASP.NET C#中的foreach获取CheckBoxList中选定项的值?
- 使用FileUpload Control获取文件的完整path
- 如何检查Request.QueryString具有特定的值或不在ASP.NET中?