Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c# get index for insertion of an item to the list which is ordered descending order

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading