Mix And Sort Files - C# Programming Exercise

In this exercise, you need to create a program that reads the contents of two different files, merges them, and sorts them alphabetically. The program should be able to take the text from both files, merge them into a single sequence of words, and then sort them alphabetically before displaying the result on the console.

For example, if the files contain the words "Dog Cat and Chair Table", the program should display the result "Cat Chair Dog Table", sorting the words in alphabetical order.

This exercise is a great way to practice file handling and string manipulation in C#, as well as using data structures such as lists or arrays to temporarily store the data read and perform the sorting.

 Category

Dynamic Memory Management

 Exercise

Mix And Sort Files

 Objective

Create a program that reads the contents of two different files, merges them, and sorts them alphabetically. For example, if the files contain: "Dog Cat and Chair Table", the program should display: "Cat Chair Dog Table".

 Write Your C# Exercise

// Importing necessary namespaces for file operations and basic collections
using System;  // Basic namespace for console input/output and fundamental operations
using System.Collections.Generic;  // For using collections like List
using System.IO;  // For file reading and writing operations

class Program
{
    // Function to read the contents of a file, split them into words, and return a sorted list
    static List ReadAndSortFile(string filePath)
    {
        // Check if the file exists before trying to read it
        if (File.Exists(filePath))  // If the file exists
        {
            // Read all lines from the file and split them into words
            string[] words = File.ReadAllText(filePath).Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);  // Read all text from the file and split by spaces and line breaks

            // Convert the array of words into a list and sort it alphabetically
            List sortedWords = new List(words);  // Create a list from the words array
            sortedWords.Sort();  // Sort the list alphabetically

            return sortedWords;  // Return the sorted list of words
        }
        else
        {
            Console.WriteLine($"The file {filePath} does not exist.");  // Print a message if the file does not exist
            return new List();  // Return an empty list if the file is not found
        }
    }

    // Main program method to read, merge, and sort the contents of two files
    static void Main(string[] args)
    {
        // Define the paths to the two input files
        string filePath1 = "file1.txt";  // Path for the first input file
        string filePath2 = "file2.txt";  // Path for the second input file

        // Read and sort the contents of both files
        List sortedWords1 = ReadAndSortFile(filePath1);  // Read and sort the first file
        List sortedWords2 = ReadAndSortFile(filePath2);  // Read and sort the second file

        // Merge the two sorted lists
        sortedWords1.AddRange(sortedWords2);  // Add the words from the second file to the first

        // Sort the merged list alphabetically
        sortedWords1.Sort();  // Sort the merged list alphabetically

        // Display the sorted words in the console
        Console.WriteLine("Merged and sorted words:");
        foreach (string word in sortedWords1)  // Iterate through the sorted words
        {
            Console.Write(word + " ");  // Display each word followed by a space
        }

        Console.WriteLine();  // Add a line break after the output
    }
}

 Share this C# exercise

 More C# Programming Exercises of Dynamic Memory Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.

  •  ArrayList of Points

    In this exercise, you need to create a structure named "Point3D" to represent a point in 3D space with X, Y, and Z coordinates. The structure should allow storing and manipu...

  •  Search in file

    In this exercise, you need to create a program that reads the contents of a text file, saves the content into an ArrayList, and prompts the user to enter sentences to...

  •  Implementing a queue using array

    In this exercise, you need to implement a queue in C#. A queue is a data structure that follows the FIFO (First In, First Out) principle, meaning the first ele...

  •  Implementing a stack using array

    In this exercise, you need to implement a stack in C#. A stack is a data structure that follows the LIFO (Last In, First Out) principle, meaning the last eleme...

  •  Queue Collections

    In this exercise, you need to create a string queue using the Queue class that already exists in the DotNet platform. The Queue class is an implementation of t...

  •  Queue Stack Reverse Polish Notation

    In this exercise, you need to create a program that reads a Reverse Polish Notation (RPN) expression from a text file, such as: 3 4 6 5 - + * 6 + (Result 21). In...