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?
2
Answers
You can do all this easily with linq.
1- using
OrderBy(x => x.Id
to order list with Id2- using
ThenBy(x=>x.Name)
to sort those with the same ID by name3- using .Select(x=>new {Id=x.Id,Name= x.Name.ToUpper()}) to convert the name to uppercase
4- using
.Distinct()
for remove duplicateFirst override
Equals
of yourperson
class for comparing 2 objects likethen you can use
linq
namespace