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 field in a list of objects by property with C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Collections.Generic;
 
public class User
{
    private string name;
    private short age;
    private string title;

    public User(string name, short age, string title) {
        this.name = name;
        this.age = age;
        this.title = title;
    }

    public string Name {
        get { return name;  }
        set { name = value; }
    }

    public short Age {
        get { return age; }
        set { age = value; }
    }
    
    public string Title {
        get { return title; }
        set { title = value; }
    }
}
 
class Program
{
    static void Main(string[] args)
    {
        List<User> UserList = new List<User>();  
        
        UserList.Add(new User("Robert", 31, "Software Developer"));
        UserList.Add(new User("Mark", 35, "Web Developer"));
        UserList.Add(new User("Jennifer", 27, "Java Developer"));
        UserList.Add(new User("Betty", 35, "Web designer"));
        UserList.Add(new User("Sharon", 41, "Web designer"));

        var sorted = UserList.OrderBy(s => s.Name);
        
        foreach (var s in sorted) {
            Console.WriteLine(s.Name);
        }
    }
}
 
 
 
/*
run:
 
Betty
Jennifer
Mark
Robert
Sharon
 
*/

 



answered Jun 5, 2024 by avibootz
...