Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am writing a web application. I have written a class

class person{<br />
  string FirstName = "";<br />
  int rank = 0;<br />
  int LastName = "";<br />
}


I have a list of "people" and want to sort them by rank - IE. highest rank first

for example.

Say I have someone called bob at a rank of 2 and someone called rob with a rank of 4 and someone called wob with a rank of 1

(I'm great with coming up with names)

I want to sort this list so the outcome would be this:

rob - 4<br />
bob - 2<br />
wob - 1


Can anyone help?
Posted

C#
public class Person{
	public string FirstName {get;set;}
	public int Rank {get;set;}
	public string LastName {get;set;}
}

List<person> personList = new List<person>();
personList.Add(new Person(){ FirstName="bob", Rank=2 });
personList.Add(new Person(){ FirstName="wob", Rank=1 });
personList.Add(new Person(){ FirstName="rob", Rank=4 });

var result =  from v in (from p in personList
                         select p).OrderByDescending(x=>x.Rank)
              select new
                  {
		ResultValue = String.Format("{0} - {1}",v.FirstName,v.Rank)
	      };

This would result
rob - 4
bob - 2
wob - 1
 
Share this answer
 
v2
Comments
Kodemaster123 27-Aug-12 4:38am    
I forgot to mention that I can't use system.linq - is there any way to do this without using this lib?
pramod.hegde 27-Aug-12 5:07am    
Then you might need to write the logic by your own.
Something like this,

Person[] personList = new Person[4]; // fill this

int n=personList.Length;
Person temp = null;

for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (personList[i].Rank < personList[i].Rank)
{
temp = personList[i];
personList[i] = personList[j];
personList[j] = temp;
}
}
}

This will sort according to the Rank.
Kodemaster123 27-Aug-12 22:29pm    
Thanks! This solved my problem!

I noticed one error in your coding though:
if (personList[i].Rank < personList[i].Rank)
should have been
if (personList[i].Rank < personList[j].Rank)

Nobody's perfect

Thanks!!!!
Kodemaster123
Where are you stuck? To get you started, you can use the IComparable<T> interface to create custom sorting of lists. Refer to the following link:

http://msdn.microsoft.com/en-us/library/4d7sx9hd.aspx[^]

http://addinit.com/node/50[^]

Hope this helps!
 
Share this answer
 
C#
List<person> ToBeSortedList ;//modify to appropriate list name

List<person> SortedbyRankPersonList = (ToBeSortedList.OrderByDescending(c => c.rank)).ToList();


Thanks,

Kuthuparakkal
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900