Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to sort a list of objects by multiple fields in C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Collections.Generic;
 
public class Lang {
    public string l;
    public int code;
 
    public Lang(string l, int code) {
        this.l = l;
        this.code = code;
    }
 
    public override string ToString() {
        return l + ", " + code;
    }
}
 
public class Example
{
    public static void Main()
    {
        Lang a = new Lang("c#", 12);
        Lang b = new Lang("c", 5);
        Lang c = new Lang("c++", 19);
        Lang d = new Lang("java", 2);
        Lang e = new Lang("java", 13);
        Lang f = new Lang("rust", 21);
        Lang g = new Lang("c", 21);
        Lang h = new Lang("python", 17);
        Lang i = new Lang("c#", 9);
 
        List<Lang> lst = new List<Lang>() { a, b, c, d, e, f, g, h, i };
 
        List<Lang> sorted_list = lst.OrderBy(x => x.l)
                                    .ThenBy(x => x.code)
                                    .ToList();
 
        Console.WriteLine(String.Join(Environment.NewLine, sorted_list));
    }
}



 
/*
run:

c, 5
c, 21
c#, 9
c#, 12
c++, 19
java, 2
java, 13
python, 17
rust, 21

*/

 



answered Mar 27, 2023 by avibootz
...