2012-08-03 50 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