简体   繁体   中英

C# Sorted list without LINQ and SORT

My question is that is it possible to create a list that sorts the objects in it upon these object being placed in them?

After not getting anywhere, I made a new linked list. The only task is to make this list ordered by the string field of the objects it will containt while remaining foreachable.

I have the following code:

class LancoltLista<T> : IEnumerable
{
    class ListaElem
    {
        public T tartalom;
        public ListaElem kovetkezo;
    }
    ListaElem fej;
    public void ElejereBeszuras(T elem)
    {
        ListaElem uj = new ListaElem();
        uj.tartalom = elem;
        uj.kovetkezo = fej;
        fej = uj;
    }

    public void VegereBeszuras(T elem)
    {
        if (fej == null)
        {
            ElejereBeszuras(elem);
        }
        else
        {
            ListaElem e = fej;
            while (e.kovetkezo != null)
            {
                e = e.kovetkezo;
            }
            ListaElem uj = new ListaElem();
            uj.tartalom = elem;
            e.kovetkezo = uj;
        }
    }

    public IEnumerator GetEnumerator()
    {
        return new ListaBejaro(fej);
    }

    class ListaBejaro : IEnumerator<T>
    {
        ListaElem elso, jelenlegi;

        public ListaBejaro(ListaElem elso)
        {
            this.elso = elso;
            jelenlegi = null;
        }


        public bool MoveNext()
        {
            if (jelenlegi == null)
            {
                jelenlegi = elso;
            }
            else
            {
                jelenlegi = jelenlegi.kovetkezo;
            }
            return jelenlegi != null;
        }

        public void Reset()
        {
            jelenlegi = null;
        }

        object IEnumerator.Current
        {
            get { return this.jelenlegi.tartalom; }
        }

        public T Current
        {
            get { return this.jelenlegi.tartalom; }
        }

        public void Dispose()
        {
            elso = null;
            jelenlegi = null;
        }
    }
}

The problem here is that I'm not able to compare p.kulcs and kulcs.

For real world applications you could use the built-in SortedList<T> .

For your homework, you will have to check every item that you get in your add method against the entire list and insert it into the correct place: between the last element that it's grater than or equal to, and the first element that it's smaller then.
Of course, if the list is empty, or if there is no element greater than the one you add, then you simply append the element to the last available location.

Since this is homework, I'll leave you to write the code yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM