2009-12-30 76 views
5

我有這樣一個清單:Lambda表達式如何在列表<String>上執行String.Format?

List<String> test = new List<String> {"Luke", "Leia"}; 

我想用這樣的:

test.Select(s => String.Format("Hello {0}", s)); 

,但不調整在列表中的名稱。有沒有辦法使用lambda表達式來改變這些?還是因爲字符串是不可變的,這是行不通的?

回答

12

Select不修改原始集合;它創建一個新的IEnumerable <牛逼>,你可以用的foreach枚舉或轉換到一個列表:

List<String> test2 = test.Select(s => String.Format("Hello {0}", s)).ToList(); 

測試仍然包含「盧克」「累啊」TEST2包含「你好盧克」「你好萊亞」


如果要修改原來的列表與lambda表達式,你可以將lambda表達式每個項目單獨和結果存回集合中:

Func<string, string> f = s => String.Format("Hello {0}", s); 

for (int i = 0; i < test.Count; i++) 
{ 
    test[i] = f(test[i]); 
} 
+0

謝謝,第一個成功對我來說。 – 2009-12-30 15:06:50

+0

@Nyla Pareska:該版本不會修改似乎是您的意圖的原始集合(「但它不會調整列表中的名稱」)。如果你想這樣做,請參閱我在答案中提供的擴展方法。 – jason 2009-12-30 15:10:15

-2

你可以只做一個foreach語句:

test.ForEach(s=>String.Format("Hello {0}", s)); 

這就是如果你只是想更新名稱。

+2

ForEach採取'Action '並且不修改'List ' – dtb 2009-12-30 14:42:58

+1

String.Format返回一個新字符串,但不修改原始字符串。 – M4N 2009-12-30 14:43:44

+0

好的,所以更新它:s => s = String.Format(「Hello {0}」,s));這一切都取決於他想要做什麼,返回帶有更新值的新列表或更新原始列表。 – 2009-12-30 14:56:27

3

這裏:

for(int i = 0; i < test.Count; i++) { 
    test[i] = String.Format("Hello {0}", test[i]); 
} 

無需被看中。無需濫用LINQ。只是保持簡單。

你可以走一步超越這一點,並創建一個擴展方法,像這樣:

static class ListExtensions { 
    public static void AlterList<T>(this List<T> list, Func<T, T> selector) { 
     for(int index = 0; index < list.Count; index++) { 
      list[index] = selector(list[index]); 
     } 
    } 
} 

用法:

test.AlterList(s => String.Format("Hello {0}", s)); 

Select是突出的,並且真的打算在情況那裏使用沒有副作用。非常清楚地操作列表中的項目有副作用。事實上,行

test.Select(s => String.Format("Hello {0}", s)); 

沒有做任何事情,除了創造一個IEnumerable<string>,最終可能被過度列舉產生的投影。

+1

我不明白他將如何濫用LINQ。他會完全按照它的意圖使用它。他的問題還特別提出瞭如何使用lambda表達式來執行任務。 – 2009-12-30 14:55:01

+1

「選擇」並不意味着用於引起副作用。 – jason 2009-12-30 14:58:51

+0

@Downvoter:請留下評論,爲什麼你downvoted。 – jason 2009-12-30 15:05:23

0

另外一個可能的解決方案:

List<String> test = new List<String> {"Luke", "Leia"}; 
List<string> FormattedStrings = new List<string>(); 
test.ForEach(testVal => FormattedStrings.Add(String.Format("Hello {0}", testVal)));