0

I have code below, but i was confused how to make lambda expression with "Select" keyword to bind to list of string. But how if the method which i want to call is having 2 or more parameter My question is How do i make lambda expression

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

1 Answer 1

6

This is all you need:

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

Basically, create a new lambda (Func<string, TwoWords>) that calls the function the way you'd like.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, i am still a novice in lambda expression.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.