2013-02-26 66 views
0

我有一个枚举为: -如何转换一个枚举列表和替换“_”与“”(空格)

public enum EnumType 
    { 
     Type1_Template, 
     Type2_Folders, 
     Type3_Template, 
     Type1_Folders, 
    } 

现在,在我的控制,我想

  1. 枚举列表和
  2. 用空格替换下划线。

所以对于: - 获取枚举的名单上有

return new Models.DTOObject() 
      { 
       ID = model.id, 
       Name = model.Name, 
       Description = model.Description, 
       //Type is the property where i want the List<Enum> and replace the underscore with space 
       Type = Enum.GetValues(typeof(EnumType)).Cast<EnumType>().ToList() 
      }; 

但现在,我想这样的事情(可能听起来不可思议,虽然): -

return new Models.Customers() 
      { 
       ID = model.id, 
       Name = model.Name, 
       Description = model.Description, 
       //Type is the property where i want the List<Enum> and replace the underscore with space 
       Type = Enum.GetValues(typeof(EnumType)).Cast<EnumType>().ToList().Select(e => new 
       { 
        Value = e, 
        Text = e.ToString().Replace("_", " ") 
       }) 
      }; 

但抛出语法错误(';'缺失)。尽管这只是一种尝试。请让我知道我该如何实现它。

+1

“但抛出语法错误”不是一个明确的错误描述。 *什么*错误? – 2013-02-26 07:37:48

回答

7

你应该能够只是做

Enum.GetNames(typeof(EnumType)).Select(item => item.Replace('_',' ')); 
+0

完美的作品+1 :)谢谢!正是我想要的。 – Shubh 2013-02-26 07:51:38

+0

@shubh记得标记为正确的答案;) – dutzu 2013-02-26 07:55:18

+0

埃伊先生!标记为正确:) – Shubh 2013-02-26 08:38:11

0

您应该使用

string[] names = Enum.GetNames(typeof(EnumType)); 

之后,您可以使用一个for循环(或类似的东西)和替换“_”与“”。

for(int i = 0; i < names.Length; i++){ 
    names[i].Replace('_',' '); 
} 

参见MSDN;

+1

你特别想避免使用LINQ的任何理由? – 2013-02-26 07:39:34

+0

我不是特别习惯它... – 2013-02-26 07:42:16