0

我有下面的代码,但我很困惑如何使用“Select”关键字制作 lambda 表达式以绑定到字符串列表。但是,如果我要调用的方法有 2 个或更多参数,我的问题是如何制作 lambda 表达式

    //this code below is error
    //List<TwoWords> twoWords = stringlist.Select(CreateTwoWords(1,2)) 
    //                      .ToList();

class Program
{
    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 void setvalues(string words,int start, int length)
        {
            word1 = words.Substring(start, length);
            word2 = words.Substring(start, length);
        }
    }

    static void Main(string[] args)
    {
        List<string> stringlist = new List<string>();
        stringlist.Add("word1 word2");
        stringlist.Add("word3 word4");

        //i called createTwoWords with 1 parameter
        List<TwoWords> twoWords = stringlist.Select(CreateTwoWords)
                                .ToList();

        //i was confused how to make lamda experesion to call method with parameter 2 or more
        //this code below is error
        //List<TwoWords> twoWords = stringlist.Select(CreateTwoWords(1,2)).ToList(); 

    }

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

    private static TwoWords CreateTwoWords(string words, int start, int length)
    {
        var ret = new TwoWords();
        ret.setvalues(words, start, length);
        return ret;
    }
}
4

1 回答 1

6

这就是你所需要的:

stringlist.Select(str => CreateTwoWords(str, 1, 2)).ToList();

基本上,创建一个新的 lambda ( Func<string, TwoWords>) 以您想要的方式调用该函数。

于 2013-10-30T02:43:50.263 回答