9

LINQこのオブジェクトの中に新しいtwoWordsオブジェクトを選択しList、関数/メソッドを呼び出して値を設定するために使用しています。

これが理にかなっているかどうかを確認してください。私はそれを大幅に簡略化しました。私は本当にlinqステートメントを使いたいですfrom select

の最初の関数は機能しGOGO、2番目の関数は失敗します(ただし、同じタスクは実行されません)

// 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();
    }
}

の2番目の関数はGOGOエラーを引き起こします:

select句の式のタイプが正しくありません。'Select'の呼び出しで型推論が失敗しました。

私の質問は、関数を使用して値を設定しながら、上記の句で新しいtwoWordsオブジェクトを選択するにはどうすればよいですか?fromsetvalues

4

1 に答える 1

27

ステートメントラムダを使用する必要があります。これは、クエリ式を使用しないことを意味します。この場合、選択したものしかないので、とにかくクエリ式は使用しません...

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 に答える