9

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

4

1 回答 1

27

您需要使用语句 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一个从一开始就做正确事情的构造函数,此时您不仅需要调用方法......

于 2012-08-03T09:37:45.550 回答