Home > Enterprise >  Wrong result for sorting list with two items and converting to upper case in C#
Wrong result for sorting list with two items and converting to upper case in C#

Time:01-10

I have a class called person which contains id and name. And I have a list of person. I want to sort the list by Id. Then, sort those with the same ID by name and convert the name to uppercase letters and finally, duplicate items are removed.

List<person> list = new List<person>();
list.Add(new person(112, "Bname"));
list.Add(new person(111, "Cname"));
list.Add(new person(112, "Aname"));
list.Add(new person(111, "Aname"));
list.Add(new person(114, "Aname"));

desired output:

111,ANAME
111,CNAME
112,ANAME
112,BNAME
114,ANAME

my code:

       for (int i = 0; i < list.Count - 1; i  )
        {

            if (list[i   1].Id < list[i   1].Id && string.Compare(list[i   1].Name, list[i   1].Name) > 0)
            { 
                person temp = list[i];
                list[i] = list[i   1];
                list[i   1] = temp;
                i = -1; //sort from lowest out of order index
            }
        }

        for (int i = 0; i < list.Count - 1; i  )
        {
            list[i].Name= list[i].Name.ToUpper();
            if (list[i] == list[i   1])
                list.Remove(list[i   1]);
        }

But the result is wrong.can someone help me?

CodePudding user response:

You can do all this easily with linq.

1- using OrderBy(x => x.Id to order list with Id

2- using ThenBy(x=>x.Name) to sort those with the same ID by name

3- using .Select(x=>new {Id=x.Id,Name= x.Name.ToUpper()}) to convert the name to uppercase

4- using .Distinct() for remove duplicate

  var result=list.OrderBy(x => x.Id).ThenBy(x=>x.Name)
                 .Select(x=>new {Id=x.Id,Name= x.Name.ToUpper()}).Distinct().ToList();

CodePudding user response:

First override Equals of your person class for comparing 2 objects like

public override bool Equals(object? obj)
    {
        return Id == (obj as person)?.Id && Name == (obj as person)?.Name;
    }

then you can use linq namespace

list = list.OrderBy(x => x.Id).ThenBy(x => x.Name).ToList();
list.ForEach(x => x.Name = x.Name.ToUpper());
list = list.Distinct().ToList();
  • Related