Skip to content
June 30, 2010 / windperson

Linq的好用處之一

一個字串陣列{“test1”, “test2”, “test3”, “test4”, “test5”, “test6”},要把每個字串用自定義的串接符號,最後產生一個總和的字串時,以往都得用迴圈自己加上去,還要注意開頭和結尾不要多加了串接符號,現在用Linq的Aggregate()卻很簡單:

string sep = " | ";
string[] lst = {"test1", "test2", "test3", "test4", "test5", "test6"};
string str = lst.Aggregate((s1, s2) => string.Format("{0}"+ sep +"{1}", s1, s2));

這樣最後的結果字串str就是『test1 | test2 | test3 | test4 | test5 | test6』,相當方便Thumbs up

加強版的問題來了…現在有{“aa”,”bb”,”cc”,”dd”,”ee”,”ff”,”gg”}這個陣列叫ids,然後想要產生『‘aa’,’bb’,’cc’,’dd’,’ee’,’ff’,’gg’』這樣的字串,於是乎一開始很直覺地這樣寫:

string result = ids.Aggregate((s1,s2) => "'"+s1+"','"+s2+"'");

產生的結果字串卻是:『”””aa’,’bb”,’cc”,’dd”,’ee”,’ff”,’gg’』→完全不對Annoyed

後來想到,這要分兩步驟來做,首先是把每個字串元素前後加「」號,然後依序把每個元素用「,」串起來:
string result = ids.Select(s => string.Format("'{0}'",s)).Aggregate((s1,s2) => s1+","+s2);

結果就是對的了Party smile

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: