2012-08-03 100 views
6

我正在使用LINQ來選擇一個新的twoWords對象到這個對象的List中,並通過調用一個函數/方法來設置這些值。LINQ選擇新對象,設置函數中對象的值

請看看這是否合理,我已經簡化了很多。我真的想用linq語句fromselect

GOGO第一個函數將工作,第二個失敗(他們不執行,雖然同樣的任務)

// simple class containing two strings, and a function to set the values 
public class twoWords 
{ 
    public string word1 { get; set; } 
    public string word2 { get; set; } 

    public void setvalues(string words) 
    { 
     word1 = words.Substring(0,4); 
     word2 = words.Substring(5,4); 
    } 
} 

public class GOGO 
{ 

    public void ofCourseThisWillWorks() 
    { 
     //this is just to show that the setvalues function is working 
     twoWords twoWords = new twoWords(); 
     twoWords.setvalues("word1 word2"); 
     //tada. object twoWords is populated 
    } 

    public void thisdoesntwork() 
    { 
     //set up the test data to work with 
     List<string> stringlist = new List<string>(); 
     stringlist.Add("word1 word2"); 
     stringlist.Add("word3 word4"); 
     //end setting up 

     //we want a list of class twoWords, contain two strings : 
     //word1 and word2. but i do not know how to call the setvalues function. 
     List<twoWords> twoWords = (from words in stringlist 
          select new twoWords().setvalues(words)).ToList(); 
    } 
} 

GOGO第二個功能將導致錯誤:

的select子句中的表達式類型不正確。在對「選擇」的調用中,類型推斷失敗。

我的問題是,我該如何選擇上面from子句中的新twoWords對象,而使用setvalues功能設定值是多少?

+4

另外,它*真*有助於可讀性,如果你遵循.NET命名約定,即使是簡單的示例代碼。 – 2012-08-03 09:38:48

回答

18

您需要使用語句lambda,這意味着不使用查詢表達式。在這種情況下我不會用一個查詢表達式反正,因爲你只有一個選擇......

List<twoWords> twoWords = stringlist.Select(words => { 
               var ret = new twoWords(); 
               ret.setvalues(words); 
               return ret; 
              }) 
            .ToList(); 

或者,只是它返回一個適當twoWords的方法:

private static twoWords CreateTwoWords(string words) 
{ 
    var ret = new twoWords(); 
    ret.setvalues(words); 
    return ret; 
} 

List<twoWords> twoWords = stringlist.Select(CreateTwoWords) 
            .ToList(); 

這也將讓你使用一個查詢表達式,如果你真的想:

List<twoWords> twoWords = (from words in stringlist 
          select CreateTwoWords(words)).ToList(); 

當然,另一種辦法是給twoWords構造whic h做了正確的事情開始,在這一點上,你不會只需要調用一個方法...

+0

謝謝喬恩。這絕對適用於我的問題。爲了感興趣,如果我確實希望使用查詢表達式,並保持twoWords類的原樣?這可能嗎? 我的實際選擇看起來是這樣的: 名單 twoWords =(從xmlDoc.Descendants菜單( 「MENU」) 在哪裏(在menu.Elements字符串)menu.Attribute( 「類型」)== menuType 從字( 「item」) select new twoWords()。setAttributes(words) ) .ToList(); – 2012-08-03 10:10:07

+1

@DavidSmit:你可以做到這一點,但只能使用輔助方法(按照底部)。查詢表達式*僅*允許表達式lambda表達式。 – 2012-08-03 10:24:52

+0

感謝Jon的幫助! – 2012-08-03 11:10:12