Click here to Skip to main content
15,880,469 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi guys,

I'm creating a simple application that that takes firstName and surName input from text boxes, adds them to a List (currently using List) and a ListBox by clicking on a "Add" button. And I also have a button that has to sort the names in alphabetical order, but the catch is that it has to sort them by using the surname not first name.

I got to a point where I can add the names but when I click the sort, the first names vanish from the listBox and only the surnames are shown. I need to somehow merge them or change the data structure so the first names and surnames are linked.

The major problem is that the tasks requires me to sort the names without using any pre-defined sort methods.


C#:
C#
namespace Sorting
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public List<string> fnameList = new List<string>();
        public List<string> surnameList = new List<string>();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnSort_Click(object sender, RoutedEventArgs e)
        {
            lstOutput.Items.Clear();
            string swap;

            for(int i = 0; i < surnameList.Count; i++)
            {
                for(int j = 0; j < surnameList.Count; j++)
                {
                    if(string.Compare(surnameList[i], surnameList[j]) < 0)
                    {
                        swap = surnameList[i];
                        surnameList[i] = surnameList[j];
                        surnameList[j] = swap;
                    }
                }      
            }

            foreach(var item in surnameList)
            {
                lstOutput.Items.Add(item);
            }
            
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            if(txtFname.Text == "" || txtSurname.Text == "")
            {
                MessageBox.Show("\t\tError\n\n\tInput a valid first name or/and surname");
                return;
            } 
            else
            {
                //adds names to lists
                fnameList.Add(txtFname.Text);
                surnameList.Add(txtSurname.Text);

                lstOutput.Items.Add(txtFname.Text + " " + txtSurname.Text);

                txtFname.Text = "";
                txtSurname.Text = "";
            }
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            txtFname.Text = "";
            txtSurname.Text = "";
            lstOutput.Items.Clear();
            fnameList.Clear();
            surnameList.Clear();
        }


    }
}


XAML
XML
<pre><Window x:Class="Sorting.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Sorting"
        mc:Ignorable="d"
        Title="MainWindow" Height="570" Width="500" WindowStartupLocation="CenterScreen" ResizeMode="NoResize">
    <Grid>
        <TextBlock HorizontalAlignment="Left" Height="28" Margin="149,20,0,0" TextWrapping="Wrap" Text="Sorting Algorithm" VerticalAlignment="Top" Width="198" FontFamily="Arial" FontSize="22" FontWeight="Bold"/>
        <TextBox x:Name="txtFname" HorizontalAlignment="Left" Height="29" Margin="304,108,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="138"/>
        <TextBox x:Name="txtSurname" HorizontalAlignment="Left" Height="29" Margin="303,170,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="139"/>
        <Button x:Name="btnAdd" Content="Add" HorizontalAlignment="Left" Height="50" Margin="303,228,0,0" VerticalAlignment="Top" Width="158" Click="btnAdd_Click"/>
        <ListBox x:Name="lstOutput" HorizontalAlignment="Left" Height="448" Margin="21,68,0,0" VerticalAlignment="Top" Width="265" FontFamily="Arial" BorderBrush="Black"/>
        <Button x:Name="btnClear" Content="Clear" HorizontalAlignment="Left" Height="46" Margin="349,289,0,0" VerticalAlignment="Top" Width="74" Click="btnClear_Click"/>
        <Button x:Name="btnSort" Content="Sort" HorizontalAlignment="Left" Height="82" Margin="301,434,0,0" VerticalAlignment="Top" Width="162" FontFamily="Arial" Click="btnSort_Click"/>
        <Label Content="First Name:" HorizontalAlignment="Left" Height="26" Margin="300,84,0,0" VerticalAlignment="Top" Width="88" FontFamily="Arial"/>
        <Label Content="Surname: " HorizontalAlignment="Left" Height="26" Margin="300,147,0,0" VerticalAlignment="Top" Width="88" FontFamily="Arial"/>
    </Grid>
</Window>


What I have tried:

I'm almost certain from all the stuff I read, that I need a Dictionary.. But my coding knowledge is not that good at this point to implement it efficiently.
Posted
Updated 22-Nov-20 9:26am
Comments
BillWoodruff 23-Nov-20 1:48am    
"the tasks requires me to sort the names without using any pre-defined sort methods."

Why ?

Define a class, with the two values, a ToString for displaying them together, and a compare method which sorts by last then first.
 
Share this answer
 

My choice would be to use a value Tuple. Like this:


C#
public List<(string surname, string forename)> namesList = new List<(string surname, string forename)>();
//add an item
namesList.Add((txtSurname.Text, txtFname.Text));
lstOutput.Items.Add(txtFname.Text + " " + txtSurname.Text);
//ascending sort items and output result
lstOutput.Items.Clear();
 namesList.Sort((x, y) => {
 int result = x.surname.CompareTo(y.surname);
 return result == 0 ? x.forename.CompareTo(y.forename) : result;
 });

 foreach (var name in namesList)
  {
    lstOutput.Items.Add($"{name.surname}  { name.forename}");
  }

An alternative approach.


C
public List<string>; namesList = new List<string >;();
//Add to List
namesList.Add($"{txtSurname.Text}~{txtFname.Text}");
lstOutput.Items.Add(txtFname.Text + " " + txtSurname.Text);
txtFname.Text = "";
txtSurname.Text = "";
//sort
lstOutput.Items.Clear();
string[] namesArray = namesList.ToArray();
Array.Sort(namesArray);
foreach (var name in namesArray)
 {
   var sorted = name.Split('~');
   lstOutput.Items.Add($"{sorted[0]}  {sorted[1]}");
 }
 
Share this answer
 
v2
Comments
Morke97 22-Nov-20 16:29pm    
It works, but can you show me how to do it without the Sort() function.

Task rules, unfortunately.
George Swan 22-Nov-20 17:15pm    
Please see the alternative approach that I have appended to my answer.
Morke97 23-Nov-20 4:39am    
Thank you!
George Swan 23-Nov-20 4:46am    
You are very welcome - I know how frustrating coding can be

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900