inserting element into a list, if condition is met with C#

c#, list

Solution

You could do something like this:

int index = list1.BinarySearch(must_enter);
if (index < 0)
 list1.Insert(~index, must_enter);

This way you will keep the list sorted with the best possible performance.

Problem

How to insert some number into the middle of the list, if there is no such number present? In the example below I'm trying to insert number 4 ``` List<int> list1 = new List<int>(){ 0, 1, 2, 3, 5, 6 }; int must_enter = 4; if (!list1.Contains(must_enter)) { list1.Add(must_enter); } ``` As the result number will be entered at the end of the list, but I want it right after 3 (before 5). please note that due to project's specifics I can't use sorted list, but all numbers in the list are guaranteed to be in ascending order (0,2,6,9,10,...) EDIT: I knew about an error and that's what I did: ``` List<int> list0 = new List<int>() { 1, 2, 3, 5, 6 }; int must_enter = 7; if (!list0.Contains(must_enter)) { if (must_enter < list0.Max()) { int result = list0.FindIndex(item => item > must_enter || must_enter > list0.Max()); list0.Insert(result, must_enter); } else { list0.Add(must_enter); } } ``` edit2: anyway I've switched to BinarySearch method due to several factors. Everyone thanks for your help!

Original source