2011-06-03 22 views
0

是我使用當前但不知道代碼有沒有這樣做我在做什麼更好的辦法......我創建像A B C dé....ž創建A-Z下面條

任何想法A-Z模式?

if (myEnum.MoveNext()) 
{ 
    MyNames t = myEnum.Current; 

    if (t.Name.ToLower().StartsWith("a")) 
    { 
     if (_a == 0) 
     { 
      l = new Literal(); 
      //..... 
      _a = 1; 
     } 
    } 
    if (t.Name.ToLower().StartsWith("b")) 
    { 
     if (_b == 0) 
     { 
      l = new Literal(); 
      l.Text = "<h1 id='B'><span>B</span></h1>" + Environment.NewLine; 
      _b = 1; 
     } 
    } 
    .....c..d...e...f...g....z 
} 
+0

什麼是家庭作業標籤? – 2011-06-03 20:31:38

+2

你在問什麼? – Oded 2011-06-03 20:31:48

+0

@Anthony編輯我的問題,並將我的問題標記爲「家庭作業」,但我現在沒有看到,可能是他刪除了 – 2011-06-03 20:34:18

回答

1

您也可以使用帶有LINQ「聚合」功能。

string[] list = { "a", "b", "c" }; 

var output = list.Aggregate("", (current, listitem) => current + (Environment.NewLine + "<h1 id='" + listitem.ToUpper() + "'><span>" + listitem.ToUpper() + "</span></h1>")); 
+0

我覺得這個代碼非常相似,我需要基於我目前的設置。 – 2011-06-04 01:37:53

3

它看起來像你直接使用收集的調查員會和硬編碼特定代碼的每個字母。據推測,每個字母的輸出應該是相同的,唯一的區別是字母本身。我會廢棄你當前的代碼,而是做如下的事情。

// note: replace yourList with the correct collection variable 
var distinctLetters = 
    yourList.Select(item => item.Name.Substring(0,1).ToUpper()) 
      .Distinct() 
      .OrderBy(s => s); 

StringBuilder builder = new StringBuilder(); 
foreach (string letter in distinctLetters) 
{ 
    // build your output by Appending to the StringBuilder instance 
    string text = string.Format("<h1 id='{0}'><span>{0}</span></h1>" + Environment.NewLine, letter); 
    builder.Append(text); 
} 

string output = builder.ToString(); // use output as you see fit 

對於包含姓名Alpha, Charlie, Delta, Alpha, Bravo列表,輸出將是

<h1 id='A'><span>A</span></h1> 
<h1 id='B'><span>B</span></h1> 
<h1 id='C'><span>C</span></h1> 
<h1 id='D'><span>D</span></h1> 
+0

什麼是yourList和項目將?我嘗試類似但沒有工作'var distinctLetters = t.Select(t.Name.Substring(0,1).ToUpper())。Distinct();'因爲t是我的枚舉列表 – 2011-06-03 20:40:49

+0

對不起,我有一個錯字,我會給答案增加一點說明。 – 2011-06-03 20:42:42

+0

@Anthony:我沒有收藏,但我只是一次收到一行,在那種情況下你會怎麼做? – 2011-06-03 21:01:43