LINQ select a new object by setting the values ​​of the object in the function

I use LINQ to select a new twoWords object in the List for these objects and set the values ​​by calling the function / method.

Please see if this makes sense, I simplified it. I really want to use linq from select expressions.

The first function in GOGO will work, the second will fail (they do not perform the same task)

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

The second GOGO function will GOGO error:

The type of expression in the select clause is invalid. Type input error in select call.

My question is: how to select a new twoWords object in the above from clause by setting values ​​using the setvalues function?

+6
source share
1 answer

You need to use the lambda operator, which means not using a query expression. In this case, I would not use a query expression, given that you only have a choice ...

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

Or, alternatively, just enter a method that returns the corresponding twoWords :

 private static twoWords CreateTwoWords(string words) { var ret = new twoWords(); ret.setvalues(words); return ret; } List<twoWords> twoWords = stringlist.Select(CreateTwoWords) .ToList(); 

This will also allow you to use a query expression if you really wanted to:

 List<twoWords> twoWords = (from words in stringlist select CreateTwoWords(words)).ToList(); 

Of course, another option would be to give the twoWords constructor a constructor that did the right thing, and at that point you just would not need to call the method ...

+18
source

Source: https://habr.com/ru/post/922025/


All Articles