LINQ选择新对象,在函数中设置对象的值

Dav*_*mit 6 c# linq list

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

第二个功能GOGO会导致错误:

select子句中表达式的类型不正确.在"选择"调用中类型推断失败.

我的问题是,twoWordsfrom使用setvalues函数设置值时,如何在上面的子句中选择新对象?

Jon*_*eet 21

您需要使用语句lambda,这意味着不使用查询表达式.在这种情况下,我不会使用查询表达式,因为你只有一个选择...

List<twoWords> twoWords = stringlist.Select(words => {
                                                var ret = new twoWords();
                                                ret.setvalues(words);
                                                return ret;
                                            })
                                    .ToList();
Run Code Online (Sandbox Code Playgroud)

或者,只需要一个返回适当的方法twoWords:

private static twoWords CreateTwoWords(string words)
{
    var ret = new twoWords();
    ret.setvalues(words);
    return ret;
}

List<twoWords> twoWords = stringlist.Select(CreateTwoWords)
                                    .ToList();
Run Code Online (Sandbox Code Playgroud)

如果您真的想要:这也可以让您使用查询表达式:

List<twoWords> twoWords = (from words in stringlist 
                           select CreateTwoWords(words)).ToList();
Run Code Online (Sandbox Code Playgroud)

当然另一个选择是给twoWords一个做正确事情的构造函数,这时你不需要调用一个方法......