using System; using System.Collections.Generic; using System.Linq; using System.Text; class StudentInfo : IComparable { public StudentInfo(string ln, string fn, int id, string a) { lastName = ln; firstName = fn; idNumber = id; address = a; } public int CompareTo(object obj) { StudentInfo s = (StudentInfo)obj; if (s.ID < ID) return 1; else if (s.ID > ID) return -1; else return 0; } public override string ToString() { return firstName+" "+lastName+" "+idNumber+" " +address; } public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } public string Address { get { return address; } set { address = value; } } public int ID { get { return idNumber; } set { idNumber = value; } } private string firstName; private String lastName; private int idNumber; private string address; } public class LINQtoObjectArray { static void Main(string[] args) { StudentInfo[] students ={ new StudentInfo("Smith", "John", 12345, "5 Bournbrook Rd"), new StudentInfo("Brown", "Alan", 23412, "Dawlish Rd"), new StudentInfo("Smith","Colin", 41253, "23 Bristol Rd"), new StudentInfo("Hughes", "Richard", 52314, "18 Prichatts Rd"), new StudentInfo("Murphy", "Paul", 16352, "37 College Rd") }; // Filter a range of ID numbers var idRange= from s in students where s.ID>19999 && s.ID<=49999 select s; //PrintArray(idRange,"Students with ID in Range 2000 to 4999"); // Order by last name and then first name var nameSorted = from s in students orderby s.LastName, s.FirstName select s; //PrintArray(nameSorted, "Students sorted in last name, first name order"); // Order by ID var IDSorted = from s in students orderby s descending select s; PrintArray(IDSorted, "Students sorted in ID order"); //Console.WriteLine("There are " + students.Count() + " students"); if (nameSorted.Any()) { // Console.WriteLine("First in list " + nameSorted.First().ToString()); //Console.WriteLine("Last in list " + nameSorted.Last().ToString()); } } public static void PrintArray(IEnumerable arr, string message) { Console.WriteLine("{0}", message); foreach (T element in arr) Console.WriteLine(" {0}", element); Console.WriteLine(); } }