• C#: Creating a List of Objects from a List of strings

    SapnaVishwas Member

    Creating a List of Objects from a List of strings in C#. What I would like to get is like this:

    First Person;  Name =  Peter
                             FavoriteColor = red
    
    Second Person;  Name =  red
                             FavoriteColor =yellow
    
    Third Person;  Name =  Adam
                             FavoriteColor =Green
    
    Fourth Person;  Name =  Green
                             FavoriteColor = violet 
    
    Fifth Person;  Name =  Harry
                             FavoriteColor = Blue
    and so forth
    

    Please note that FavoriteColor of the first person becomes the Name of the Second Person. So the name of a color in the list could actually become the name of the person and what looks like the name of a person could become the FavoriteColor of another person.

  • Adan Member

    But if you insist, all you need is a trivial loop, so just leave out the condition:

            for (int i = 0; i < list.Count - 1; i++)
    	{
    		Person person = new Person();
    		person.Name = list[i];
    		person.FavoriteColor = list[i + 1];
    		personsList.Add(person);
    	}
  • ShikhaTan Member

    I agree it does not make sense to put a word which looks like the name of a person as a Favorite Color of the next person, but this is the logic I need to implement. To put it another way, if this was the list of integers – 1, 2, 3, 4, 5, 6, 7, 8, 9 then our persons will like 1 2, 2 3, 3 4, 4 5, 5 6 and so on.

    Leaving out the condition does not make any difference to the output. I am still getting the same list of person that the version of the code with the condition did.

    Perhaps what we can do is in each run of the loop we remove the first item from the list and pass the cut down version (one word less than previously) of the list through our function, then it may give the result I need, though I do not know how to do it.

Viewing 2 reply threads
  • You must be logged in to reply to this topic.
en_USEnglish