2011-06-03 95 views
4

,所以我顯示從開始的每一個名稱的第一個字母,一路到Z如何讓這個更好的代碼和更優化的

一些事情是這樣的:

一個
安東尼
艾倫
...


鮑勃
生成器
....

Ç
Charyl
卡爾
...
ž
Zoah
....

我怎樣才能使這個代碼更優化,使用更少線?

int _a = 0; 
int _b = 0; 
int _c = 0; 
... 
... 
.. 
int _z = 0; 

protected void ListItem(List<Customer>.Enumerator cust) 
{ 

if (cust.MoveNext()) 
{ 
    Customer t = cust.Current; 

string[] list = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "v", "z" }; 
var output = list.Aggregate("", (current, listitem) => current + (Environment.NewLine + "<h1 id='" + listitem.ToUpper() + "'><span>" + listitem.ToUpper() + "</span></h1>")); 
string _name = t.Name.Substring(0, 1).ToUpper(); 


if (_name == list[0].ToUpper()) 
{ 
    if (_a == 0) 
    { 
     l = new Literal(); 
     l.Text = "<h1 id='A'><span>A</span></h1>" + Environment.NewLine; 
     ..... 
     _a = 1; 
    } 
if (_name == list[1].ToUpper()) 
{ 
    if (_b == 0) 
    { 
    l = new Literal(); 
    l.Text = "<h1 id='B'><span>A</span></h1>" + Environment.NewLine; 
    ..... 
    _b = 1; 
    } 
} 
... 
.... 
.... 
... 

doing through Z 

} 

回答

1

我會改變重複代碼這種想法。

List<char> HeaderOf = new List<char>(); 

protected void ListItem(List<Customer>.Enumerator cust) 
{ 
    if (cust.MoveNext()) 
    { 
     Customer t = cust.Current; 
     string[] list = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "v", "z" }; 
     var output = list.Aggregate("", (current, listitem) => current + (Environment.NewLine + "<h1 id='" + listitem.ToUpper() + "'><span>" + listitem.ToUpper() + "</span></h1>")); 

     char CheckMe = t.Name.Substring(0, 1).ToUpper()[0]; 
     if (!HeaderOf.Contains(CheckMe)) 
     { 
      HeaderOf.Add(CheckMe); 

      l = new Literal(); 
      l.Text = "<h1 id='" + CheckMe + "'><span>" + CheckMe + "</span></h1>" + Environment.NewLine; 
     } 
    } 
} 
+0

@Abu歡迎您。 – Aristos 2011-06-04 02:02:54

3
List<Customer> myList; 


//produces a sequence of strings with the format: 
//<h1 id="A"><span>A</span></h1> 
//Anthony<br /> 
//... 
var stringValues = 
    myList 
     .GroupBy(c => c.Name[0].ToUpper()) 
     .OrderBy(g => g.Key) 
     .Select(g => string.Format(
      "<h1 id=\"{0}\"><span>{0}</span></h1>{1}\n", 
      g.Key, 
      g.Aggregate("", (a,i) => string.Format(
       "{0}<br />\n", 
       i.Name)))); 

foreach(var stringValue in stringValues) 
{ 
    var l = new Literal(); 
    li.Text = stringValue; 
    //not sure what you're doing with the literal from here... 
} 
+0

+1好用的lambda! – 2011-06-04 00:33:45

+0

爲什麼不在標記中進行表示/佈局? – dwerner 2011-06-04 04:35:49

+0

@serotonin一次一步:) – 2011-06-04 21:28:05