NoName
NoName

Reputation: 8025

How to sort a list by the property of an object

How to sort ascending this List<ABC> by c1 element? Thank you very much!

public class ABC
{
    public string c0 { get; set; }
    public string c1 { get; set; }
    public string c2 { get; set; }
}
public partial class MainWindow : Window
{
    public List<ABC> items = new List<ABC>();
    public MainWindow()
    {
        InitializeComponent();
        items.Add(new ABC
        {
            c0 = "1",
            c1 = "DGH",
            c2 = "yes"
        });
        items.Add(new ABC
        {
            c0 = "2",
            c1 = "ABC",
            c2 = "no"
        });
        items.Add(new ABC
        {
            c0 = "3",
            c1 = "XYZ",
            c2 = "yes"
        });
    }
}

Upvotes: 0

Views: 113

Answers (4)

Haedrian
Haedrian

Reputation: 4328

.OrderBy(x => x.c1);

(or .OrderByDescending)

Yeah, LINQ makes it that easy.

Upvotes: 1

Parimal Raj
Parimal Raj

Reputation: 20595

Try something like :

var sortedItems = items.OrderBy(itm => itm.c0).ToList();  // sorted on basis of c0 property
var sortedItems = items.OrderBy(itm => itm.c1).ToList();  // sorted on basis of c1 property
var sortedItems = items.OrderBy(itm => itm.c2).ToList();  // sorted on basis of c2 property

Upvotes: 2

John Woo
John Woo

Reputation: 263893

List<ABC> _sort = (from a in items orderby a.c1 select a).ToList<ABC>();

Upvotes: 2

ColinE
ColinE

Reputation: 70160

How about this:

var sortedItems = items.OrderBy(i => i.c1);

This returns an IEnumerable<ABC>, if you need a list, add a ToList:

List<ABC> sortedItems = items.OrderBy(i => i.c1).ToList();

Upvotes: 5

Related Questions