我正在使用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