2013-02-26 44 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