Advertisement
jyoung12387

Sort List<Person> based on property value

Mar 27th, 2020
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.10 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.    
  5. namespace SortExample
  6. {
  7.     public class Program
  8.     {
  9.         public static void Main()
  10.         {
  11.             List<Person> people = new List<Person>()
  12.             {
  13.                 new Person {FirstName = "John", LastName = "Doe", Age = 33},
  14.                 new Person {FirstName = "Maragaret", LastName = "Jones", Age = 28},
  15.                 new Person {FirstName = "David", LastName = "Reyes", Age = 55},
  16.                 new Person {FirstName = "Andy", LastName = "Holmes", Age = 44}
  17.             };
  18.  
  19.             // set List<Person> equal to the sorted list based on age
  20.             people = people.OrderBy(p => p.Age).ToList();
  21.            
  22.             foreach(var p in people)
  23.             {
  24.                 Console.WriteLine(p.FullName + " - " + p.Age); 
  25.             }
  26.         }
  27.     }
  28.    
  29.     public class Person
  30.     {
  31.         public string FirstName {get; set;}
  32.         public string LastName {get; set;}
  33.         public int Age {get; set;}
  34.         public string FullName
  35.         {
  36.             get {return FirstName + " " + LastName;}
  37.         }
  38.  
  39.         public Person() {}
  40.        
  41.         public Person(string firstName, string lastName, int age)
  42.         {
  43.             this.FirstName = firstName;
  44.             this.LastName = lastName;
  45.             this.Age = age;
  46.         }
  47.     }
  48.    
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement