I am having trouble putting my list in descending order when new items are being inserted. I also want to get index. My code is as follows:
int index;
if (mylist.Count == 0)
{
mylist.Add(item);
index = 0;
return;
}
for (int i = 0; i < mylist.Count; i++)
{
if (item < mylist[i])
{
index = i;
mylist.Insert(i, item);
return;
}
}
index = mylist.Count - 1;
mylist.Add(item);
Is there an easier way of doing this?
It’s not pretty as a code. I bet there is a better way.
>Solution :
You can use Linq to simplify code:
var index = myList.TakeWhile(listItem => listItem < item).Count();
myList.Insert(item, index);
BTW, Insert will work as Add if index = List.Count.
Another point: you wrote that you want to insert in descending order, while actually your code inserts in ascending order (it inserts new item before one that is greater than inserted item).
My code as well inserts item in ascending order. If you really want descending order change condition to: TakeWhile(listItem => item < listItem)