我正在使用LINQ
将一个新twoWords
对象选择到List
这些对象中,并通过调用函数/方法来设置值。
请看看这是否有意义,我已经简化了很多。我真的很想使用 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 子句中的表达式类型不正确。调用“选择”时类型推断失败。
我的问题是,如何在使用函数设置值的同时选择twoWords
上述from
子句中的新对象setvalues
?