简体   繁体   中英

Can't make simple list operation in C#

I'm trying to make a function with list. It is to sort and delete duplicates. It sorts good, but don't delete duplictates. What's the problem?

void sort_del(List<double> slist){
        //here i sort slist
        //get sorted with duplicates

        List<double> rlist = new List<double>();
        int new_i=0;
        rlist.Add(slist[0]);
        for (i = 0; i < size; i++)
        {
            if (slist[i] != rlist[new_i])
            {
                rlist.Add(slist[i]);
                new_i++;
            }

        }

        slist = new List<double>(rlist);
        //here get without duplicates
    }

It does not work because slist is passed by value. Assigning rlist to it has no effect on the caller's end. Your algorithm for detecting duplicates seems fine. If you do not want to use a more elegant LINQ way suggested in the other answer, change the method to return your list:

List<double> sort_del(List<double> slist){
    // Do your stuff
    return rlist;
}

with double you can just use Distinct()

slist = new List<double>(rlist.Distinct());

or maybe:

slist.Distinct().Sort();

You're not modifying the underlying list. You're trying to add to a new collection, and you're not checking if the new one contains one of the old ones correctly.

If you're required to do this for homework (which seems likely, as there are data structures and easy ways to do this with LINQ that others have pointed out), you should break the sort piece and the removal of duplication into two separate methods. The methods that removes duplicates should accept a list as a parameter (as this one does), and return the new list instance without duplicates.

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