locked
Initialize List of objects RRS feed

  • Question

  • User1568091510 posted

    hi, this is my code :

     <searchresult>
    

    var resultMain = new SearchResultMain();

    // code start:
    var results = new List<SearchResult>();

    foreach (var wordToFind in wordsToFind) // wordsToFind is List<string>
    {
    results.Add(new SearchResult(<searchresult>wordToFind</searchresult>));
    }

    resultMain.Results = results;

    // is there a way to do the following directly?
    resultMain.Results = new List<SearchResult>()
    {
    // ??? = set all new SearchResult(wordToFind) from wordsToFind
    };

    </searchresult>

    Is there a way to initialize the objects directly to the resultMain.Results, and without allocation of the results?

    Cheers

    Thursday, February 21, 2019 5:00 AM

Answers

  • User1568091510 posted

    hi Yuki,

    thanks for your help.

    This is the final solution i came up with

    resultMain.Results = wordsToFind.Select(word => new SearchResult(word)).ToList();

    Anything with resultMain.Results.Add() was slower.


    Cheers

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 21, 2019 10:22 AM

All replies

  • User1520731567 posted

    Hi CharlesDev,

    Is there a way to initialize the objects directly to the resultMain.Results, and without allocation of the results?

    Do you want to copy wordsToFind to resultMain.Results?

    You could refer to the code like below:

                List<string> wordsToFind = new List<string>() { "aa", "bb" };
                SearchResultMain resultMain = new SearchResultMain();
    wordsToFind.ForEach((item) => { resultMain.Results = new List<string>() {item}; //resultMain.Results="aa","bb" });

    Best Regards.

    Yuki Tao

    Thursday, February 21, 2019 7:02 AM
  • User1568091510 posted

    hi Yuki,

    thanks for your help.

    This is the final solution i came up with

    resultMain.Results = wordsToFind.Select(word => new SearchResult(word)).ToList();

    Anything with resultMain.Results.Add() was slower.


    Cheers

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 21, 2019 10:22 AM
  • User1520731567 posted

    Hi CharlesDev,

    I'm glad that you have solved the issue by yourself.

    I suggest you could mark the post as answer.

    This will help other people who faces the same issue.

    Thank you very much.<o:p></o:p>

    Best Regards.

    Yuki Tao

    Friday, February 22, 2019 1:47 AM