c# list how to insert a new value in between two values

后端 未结 5 1290
無奈伤痛
無奈伤痛 2020-12-16 09:37

so i have a list where i need to add new values constantly but when i do i need to increment it and insert it in between two values.

List initiali         


        
相关标签:
5条回答
  • 2020-12-16 10:00
    List<int> initializers = new List <int>();
    
    initializers.Add(1);
    initializers.Add(3);
    
    int index = initializers.IndexOf(3);
    initializers.Insert(index, 2);
    

    Gives you 1,2,3.

    0 讨论(0)
  • 2020-12-16 10:07

    Use List<T>.Insert:

    initializers.Insert(index, value);
    
    0 讨论(0)
  • 2020-12-16 10:07

    For those who are looking for something more complex (inserting more than one item between 2 values, or don't know how to find the index of an item in a list), here is the answer:

    Insert one item between 2 values is dead easy, as already mentioned by others:

    myList.Insert(index, newItem);
    

    Insert more than one item also is easy, thanks to InsertRange method:

    myList.InsertRange(index, newItems);
    

    And finally using following code you can find the index of an item in list:

    var index = myList.FindIndex(x => x.Whatever == whatever); // e.g x.Id == id
    
    0 讨论(0)
  • 2020-12-16 10:09

    Another approach, if there is a computationally viable way of sorting the elements, is:

    list.Insert(num);
    // ...
    list.Insert(otherNum);
    
    // Sorting function. Let's sort by absolute value
    list.Sort((x, y) => return Math.Abs(x) - Math.Abs(y));
    
    0 讨论(0)
  • 2020-12-16 10:23

    You can just use List.Insert() instead of List.Add() to insert items at a specific position.

    0 讨论(0)
提交回复
热议问题