2010-05-12 54 views
1

是否有可能使用lambda更改與拉姆達循環(C#3.0)

for (int i = 0; i < objEntityCode.Count; i++) 
{ 
    options.Attributes[i] = new EntityCodeKey(); 
    options.Attributes[i].EntityCode = objEntityCode[i].EntityCodes; 
    options.Attributes[i].OrganizationCode = Constants.ORGANIZATION_CODE; 
} 

我的意思是說改寫了使用lambda語句做同樣的。我試着用

Enumerable.Range(0,objEntityCode.Count-1).Foreach(i=> { 
    options.Attributes[i] = new EntityCodeKey(); 
    options.Attributes[i].EntityCode = objEntityCode[i].EntityCodes; 
    options.Attributes[i].OrganizationCode = Constants.ORGANIZATION_CODE; } 
); 

但不工作 我使用C#3.0

+2

做_what_使用Lambda? – 2010-05-12 03:07:34

+0

我的意思是說使用lambda重寫語句。 我試着用Enumerable.Range(0,objEntityCode.Count-1).Foreach(i => {options.Attributes [i] = new EntityCodeKey(); options.Attributes [i] .EntityCode = objEntityCode [i]。 EntityCodes; options.Attributes [i] .OrganizationCode = Constants.ORGANIZATION_CODE; });但不起作用 – Newbie 2010-05-12 03:09:49

+1

爲什麼你想用lambdas來做它?如果你的結構依賴於索引,那麼它不適用於List.ForEach()結構和FWIW,循環是編程語言的核心部分......它如何通過*而不是*使用它們來改進你的程序? – jeffora 2010-05-12 03:12:34

回答

7

那麼你可以把它與對象初始化簡單,入手:

for (int i = 0; i < objEntityCode.Count; i++) 
{ 
    options.Attributes[i] = new EntityCodeKey 
    { 
     EntityCode = objEntityCode[i].EntityCodes, 
     OrganizationCode = Constants.ORGANIZATION_CODE 
    }; 
} 

我可能會離開它雖然...目前沒有ForEach擴展方法IEnumerable<T> - 和good reasons,雖然我知道這不是普遍持有的意見;)

在這種情況下,你仍然需要知道i爲了設置options.Attributes[i] - 除非你可以設置整個options.Attributes一氣呵成,當然......不知道有關所涉及的類型,這是相當困難的進一步提醒。

如果options.Attributes是可寫的屬性(例如數組),你可以使用:

options.Attributes = objEntityCode.Select(code => new EntityCodeKey 
    { 
     EntityCode = code.EntityCodes, 
     OrganizationCode = Constants.ORGANIZATION_CODE 
    }).ToArray(); 

如果options.Attributes實際上只是它會返回一個索引,這是行不通的一個類型的屬性。

+0

爵士,什麼是在下面 Enumerable.Range wrng(0,objEntityCode.Count - 1)。選擇(I => {options.Attributes [I] =新EntityCodeKey {EntityCode = objEntityCode [I] .EntityCodes ,OrganizationCode = Constants.ORGANIZATION_CODE}; })。ToArray(); 投擲錯誤 無法從用法推斷方法「System.Linq.Enumerable.Select (System.Collections.Generic.IEnumerable ,System.Func )'的類型參數。嘗試明確指定類型參數。 – Newbie 2010-05-12 03:23:23

+0

您的lambda表達式不會返回任何內容。這只是一個聲明。這對選擇投影並沒有什麼幫助......另一個與它「錯誤」的事情是它無緣無故地引入了一堆東西。 LINQ旨在使代碼更簡單*,而不是更復雜。 – 2010-05-12 03:26:38

0
Enumerable.Range(0, objEntityCode.Count - 1).ToList().ForEach(i => 
       { 
        options.Attributes[i] = new EntityCodeKey(); 
        options.Attributes[i].EntityCode = objEntityCode[i].EntityCodes; 
        } 
       ); 
+1

我會在你的問題上添加同樣的評論:你爲什麼要這樣做?如何比明確編寫循環更好? – jeffora 2010-05-12 03:14:53

+0

先生,我正在學習LINQ和LAMBDA ....今後我會嘗試寫這些語句。 :) – Newbie 2010-05-12 03:24:40

0
Enumerable.Range(0, objEntityCode.Count - 1).ToList().ForEach(i => 
       { 
        options.Attributes[i] = new EntityCodeKey 
        { 
         EntityCode = objEntityCode[i].EntityCodes 
         , OrganizationCode = Constants.ORGANIZATION_CODE 
        }; 

       } 
      );