Click here to Skip to main content
15,920,603 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
I have a list as
C#
List<KeyValuePair<int, NoNexusCounterparty>> listcps = noNexusCpsdict.ToList();

NoNexusCounterparty is a class object which contains list of counterparties.
How to sort this list by alphabetical order.

What I have tried:

listcps = listcps.Sort();

not working..
Posted
Updated 26-Apr-16 1:30am
Comments
Patrice T 26-Apr-16 6:06am    
Define 'not working'
Karthik_Mahalingam 26-Apr-16 6:10am    
sort by key ?

Try using OrderBy:
C#
List<KeyValuePair<int, string>> myList = new List<KeyValuePair<int, string>>();
myList.Add(new KeyValuePair<int,string>(9, "Nine"));
myList.Add(new KeyValuePair<int,string>(1, "One"));
myList.Add(new KeyValuePair<int,string>(3, "Three"));
myList = myList.OrderBy(kvp => kvp.Key).ToList();
foreach (var kvp in myList) Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);
myList = myList.OrderBy(kvp => kvp.Value).ToList();
foreach (var kvp in myList) Console.WriteLine("{0}:{1}", kvp.Key, kvp.Value);

You will get:
1:One
3:Three
9:Nine
And
9:Nine
1:One
3:Three
 
Share this answer
 
What you mean by Not working ? check out below snippet
C#
var New1 = EmpList.OrderBy(z => z.Age).ToList();

where New1 is a List<employee>.
EmpList is variable of a List<employee>.
z is a variable of Employee type.
 
Share this answer
 

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