locked
Adding and removing item from the list RRS feed

  • Question

  • Hi All,

    I want to add the items to list of size 3. 

    Say if i add 1 , then result should be

    1

    Then if i add 6 to list then result should show

     6 1

    If i add 2 to list, then result should be

    2 6 1

    and if i add 4 to list then result should show only

    4 2 6

    and again if i add 2 then result should be

    4 2 6 only(because it should not take repeated value)

    and if i add 1then it should be

    1 4 2(even though first i added "1" to list )

    Can anyone help me how to do it programmetically.

    Monday, April 29, 2013 1:01 PM

Answers

  • This should do it:

    public void AddToList(List<int> myList, int number)
            {
                if (!myList.Contains(number))
                {
                    myList.Insert(0, number);
                }
    
                while (myList.Count > 3)
                {
                    myList.RemoveAt(myList.Count - 1);
                }
            }

    And this is how your sample would work:

                List<int> list = new List<int>();
                AddToList(list, 1);
                AddToList(list, 6);
                AddToList(list, 2);
                AddToList(list, 4);
                AddToList(list, 2);
                AddToList(list, 1);

     
    Monday, April 29, 2013 2:19 PM

All replies

  • Sounds like a basic programming question.  Create a List<int>.  When you add a number, check to see if there are more than three items in the list.  If so, remove the 4th item.


    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Monday, April 29, 2013 1:45 PM
    Moderator
  • This should do it:

    public void AddToList(List<int> myList, int number)
            {
                if (!myList.Contains(number))
                {
                    myList.Insert(0, number);
                }
    
                while (myList.Count > 3)
                {
                    myList.RemoveAt(myList.Count - 1);
                }
            }

    And this is how your sample would work:

                List<int> list = new List<int>();
                AddToList(list, 1);
                AddToList(list, 6);
                AddToList(list, 2);
                AddToList(list, 4);
                AddToList(list, 2);
                AddToList(list, 1);

     
    Monday, April 29, 2013 2:19 PM
  • Cool. Thank you so much Jernaj. Its working fine.

    Tuesday, April 30, 2013 1:03 PM