2012-05-17 169 views
1

我有一個linq語句,返回一個<string,string>鍵值對列表。問題是密鑰中的所有值都需要被替換。有沒有辦法在選擇linq中進行替換,而無需遍歷整個列表?鍵值對中鍵值的更新值

var pagesWithControl = from page in sitefinityPageDictionary 
         from control in cmsManager.GetPage(page.Value).Controls 
         where control.TypeName == controlType 
         select page; // replace "~" with "localhost" 

回答

6

你不能改變的關鍵,但你可以返回與新的密鑰生成新的對象:

var pagesWithControl = from page in sitefinityPageDictionary 
        from control in cmsManager.GetPage(page.Value).Controls 
        where control.TypeName == controlType 
        select new 
          { 
          Key = page.Key.Replace("~",localhost"), 
          page.Value 
          }; 

,或者如果它必須是一個KeyValuePair:

var pagesWithControl = 
    from page in sitefinityPageDictionary 
    from control in cmsManager.GetPage(page.Value).Controls 
    where control.TypeName == controlType 
    select 
    new KeyValuePair<TKey,TValue>(page.Key.Replace("~",localhost"), page.Value); 
+0

現在想象你在方法簽名中使用KeyValuePair和params關鍵字,並想改變傳遞的KeyValuePair之一的值。 –

+0

繼續:「該更改將被複制到方法調用者。」 –