我正在使用LINQ
來選擇一個新的twoWords
對象到這個對象的List
中,並通過調用一個函數/方法來設置這些值。LINQ選擇新對象,設置函數中對象的值
請看看這是否合理,我已經簡化了很多。我真的想用linq語句from
select
。
在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
功能設定值是多少?
另外,它*真*有助於可讀性,如果你遵循.NET命名約定,即使是簡單的示例代碼。 – 2012-08-03 09:38:48