2012-05-17 109 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

继续:“该更改将被复制到方法调用者。” –