C# Lists

CK CK 3788 
Created at
Updated at  
1,152 0 0

It is a fairly common programming scenario to find ourselves with a list of identical objects. In the past,without adequate support from programming languages,we found ourselves writing a lot of searching and sorting code,and that may have put you off using lists in favour of arrays. All that has changed with C# 2.0 - its implementation of a list makes handling such lists remarkably easy
 

public class Person
{
    public int age;
    public string name;

    public Person(int age,string name)
    {
        this.age = age;
        this.name = name;
    }
}


We can create a list of Person objects and add six people like so:
 

List<Person> people = new List<Person>();
 
people.Add(new Person(50,"Fred"));
people.Add(new Person(30,"John"));
people.Add(new Person(26,"Andrew"));
people.Add(new Person(24,"Xavier"));
people.Add(new Person(5,"Mark"));
people.Add(new Person(6,"Cameron"));


C# 2.0's list mechanism provides us with a number of useful methods. Personally,I find ForEach,FindAll and Sort to be very useful. ForEach allows us access to each item in the list. FindAll allows us to search for objects in the list that match a specific condition. Sort allows us to sort the objects in the list. The following code demonstrates how we might use each of these methods:

Console.WriteLine("Unsorted list");
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}",p.age,p.name)); });
 
List<Person> young = people.FindAll(delegate(Person p) { return p.age < 25; });
Console.WriteLine("Age is less than 25");
young.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}",p.age,p.name)); });
 
Console.WriteLine("Sorted list,by name");
people.Sort(delegate(Person p1,Person p2) { return p1.name.CompareTo(p2.name); });
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}",p.age,p.name)); });
            
people.Sort(delegate(Person p1,Person p2) { return p1.age.CompareTo(p2.age); });
Console.WriteLine("Sorted list,by age");
people.ForEach(delegate(Person p) { Console.WriteLine(String.Format("{0} {1}",p.age,p.name)); });


And here is the output that we should expect:

Unsorted list
50 Fred
30 John
26 Andrew
24 Xavier
5 Mark
6 Cameron
 
Age is less than 25
24 Xavier
5 Mark
6 Cameron
 
Sorted list,by name
26 Andrew
6 Cameron
50 Fred
30 John
5 Mark
24 Xavier
 
Sorted list,by age
5 Mark
6 Cameron
24 Xavier
26 Andrew
30 John
50 Fred


 

Tags C# List List Facebook X
Comments 0
  1. Extracting the Country from IP Address
    468
  2. How to run shell command by MFC ?
    436
  3. Binary Search Sample Code
    405
  4. Double Linked List based in C++
    796
  5. String Replace Function For C#
    1,547
  6. How to print character in C# by ASCII code
    477
  7. MFC based World Wide Web HTTP Server Source Code
    459
  8. Creating and Using a CAsyncSocket Object to use CAsyncSocket
    472
  9. UDP Send and Receive Using CAsyncSocket
    1,204
  10. Using the shell to receive notification of removable media being inserted or removed
    681
  11. Adding Custom Paper Sizes To Named Printers
    647
  12. Print HTML In C# With Or Without The Web Browser Control And The Print Dialog
    972
  13. A Customizable Printing Text Class
    432
  14. Simplified .NET Printing In C#
    692
  15. How To Print Text In C#
    455
  16. Simple Example of IF/THEN using C#
    1,265
  17. Fast and Good Keyboard/Mouse Test without the message handler
    982
  18. Simple CGI Programming in C
    545
  19. C++ CGI Example working on Apache
    484
  20. Simple C# CGI working on Apache
    481
  21. How to send binary data through C# CGI app?
    994
  22. Interacting With TinyPic From C#
    1,303
  23. Creating A Watched Folder With Assigned Events
    1,658
  24. Calling Your Main Thread From A Worker Thread In C#
    546
  25. HashTable Tutorial In C#
    1,787
  26. Stack Tutorial In C#
    668
  27. Queue Tutorial In C#
    1,737
  28. Create PDF Files On the Fly in C#
    1,003
  29. How to call Visual C/C++ implemented DLL functions in C# - Simple DLLImport
    1,160
  30. Send Email Using C#
    1,377
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,613
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    245
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    244
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260