C#. Windows Forms. Example the development of application, that demonstrates work with lists and associative arrays. Classes Dictionary, List, StreamReader




Example of the development of application, that demonstrates work with lists and associative arrays. Classes Dictionary, List, StreamReader

In the topic, the example of developing the application of “Windows Forms Application” type is considered. This application demonstrates using of lists (class “List“) and using of associative arrays (class “Dictionary“).

Using this example, you’ll get the experience of working with classes Dictionary <TKey,TValue> and List<T>, which belong to the generic collections.

In the application the following tasks are realized:

  • reading data from file and displaying it in the control of type “ListBox“;
  • demonstration of use the class “StreamReader” from module System.IO, for reading the data from file;
  • demonstration of work the class Dictionary<TKey, TValue> for organizing the collection. Class stores the “key-value” pairs;
  • demonstration of work the class List<T> for organizing the dynamic array or list.

Contents


Search other websites:

Task

Develop the application of “Windows Forms Application” type by using the lists and associative arrays.

The two text files “Flight.txt” and “Tickets.txt” are given. Files includes

The files contain an unlimited number of lines. Every line of file contains the data, which are separated by symbol ‘ , ‘ (comma).

One line of file “Flight.txt” has the following structure:

  • flight number (an integer);
  • departure point (string);
  • the time of departure, hours (integer);
  • the total number of places (integer).

One line of file “Tickets.txt” has the following structure:

  • ticket number (integer);
  • flight number (integer);
  • place (integer);
  • the date of departure (string);
  • destination (floating point number);
  • arrival date (string);
  • arrival time (string);
  • price (floating point number);
  • the time of ticket sales (string).

You need solve the following tasks:

1. Read data from file “Flight.txt” and perform the following operations on them:

  • display them on the Windows-form in the control of ListBox type;
  • organize data into the collection (class Dictionary<TKey, TValue>).

2. Read data from file “Tickets.txt” and perform the following operations on them:

  • display them on the Windows-form into the control of ListBox type;
  • organize data into the dynamic array (class List<T>).

3. Show on the form the flights with a maximum duration of the flight.

The calculation must be realized by using the classes Dictionary<TKey, TValue> and List<T>.

4. Show on the form the number of passengers who are waiting for the departure in the entered time. The calculation must be realized by using the classes Dictionary<TKey, TValue> and List<T>.

An example of the contents of Flight.txt file:

1,Kiev,18,120
2,Kiev ,19,100
3,Kiev,20,90
4,Kiev,22,150

An example of the contents of “Tickets.txt” file:

1,1,1,05.10.2016,California,06.10.2016,21,500,14:10
2,1,1,05.10.2016,California,06.10.2016,21,500,14:30
3,2,1,05.10.2016,Croatia,06.10.2016,22,245,14:45
4,2,2,05.10.2016,Croatia,06.10.2016,22,245,14:50
5,2,3,05.10.2016,Croatia,06.10.2016,22,245,14:51
6,3,1,05.10.2016,Amsterdam,06.10.2016,23,400,14:55
7,3,3,05.10.2016,Amsterdam,06.10.2016,23,400,15:10
8,3,7,05.10.2016,Amsterdam,06.10.2016,23,400,15:25
9,4,1,05.10.2016,Moscow,06.10.2016,24,350,15:27
10,4,10,05.10.2016,Moscow,06.10.2016,24,350,16:08

 

Performing

1. Run MS Visual Studio.

Create the project as Windows Forms Application using the template C#.

An example of creating such project is described in detail here.

 

2. Creating the form of application.

Place on the form the following controls (Figure 1):

  • control of type ListBox to displaying the data from file “Flights.txt“. Automatically the object with name listBox1 is created;
  • control of type Label to displaying the data from file “Tickets.txt“. Automatically the object with name listBox2 is created;
  • controls of type Label for displaying the messages. The objects named label1, label2, label3, label4, label5 are created;
  • control of type TextBox which represents the string of data input (departure time). The object named textBox1 is created;
  • control of type Button (button “Calculate“). The object named button1 is created;
  • control of type ListBox (list of flights with a maximum duration of flight). The object named listBox3 is created.

Correct the size and positions of controls as shown in Figure 1.

C# - Windows Forms. The program form after placement the controlsFig. 1. The program form after placement the controls

 

3. Setting of control properties.

Setting of control properties is realized by using the “Properties” window of Microsoft Visual Studio 2010.

Set up the following properties of controls:

  • in the control label1 property Text = “File Flight.txt”;
  • in the control label2 property Text = “File Tickets.txt”;
  • in the control label3 property Text = “Departure time”;
  • in the control textBox1 property Text = “”;
  • in the control label4 property Text = “The number of passengers who are waiting for the departure: “;
  • in the control button1 property Text = “Calculate”;
  • in the control label5 property Text = “Flights with maximum duration of the flight: “.

After setting the properties and correcting the positions and size of controls the main form of application will be as shown in Figure 2.

C# - Windows Forms. The program form after configuringFigure. 2. Application form after setting the controls

 

4. The organization of data in the form of structures.

You need to represent as a structure, the data that are placed in one line of any file. It is needed to increase the efficiency work of program. Unlike classes, that are links, the structures are realized as value types. Compared to structures, to access the object of class is needed more allocated memory and resources.



We represent data of one line in the file “Flight.txt” like structure Flight:

// Structure "Flights"
public struct Flight
{
    public int num_r; // number of flight
    public string punkt_vd; // point of departure
    public int time_v; // departure time
    public int n_places; // the number of seats
}

By the same principle are provided data of one line of the file “Tickets.txt” in the structure Tickets:

// Structure "Tickets"
public struct Tickets
{
    public int num_t; // number of ticket
    public int num_r; // number of flight
    public int place; // place
    public string date_v; // flight date
    public string punkt_pr; // destination
    public string data_pr; // arrival date
    public int time_pr; // arrival time
    public double price; // price
    public string time_prod; // the time of ticket sales
}

After inputting the structures, a code snippet of file “Form1.cs” is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Kontrolna_UZHNU_1
{
  public partial class Form1 : Form
  {
    // structure Flight
    public struct Flight
    {
      public int num_r; // number of flight
      public string punkt_vd; // point of departure
      public int time_v; // departure time
      public int n_places; // the number of seats
    }

    public struct Tickets
    {
      public int num_t; // number of ticket
      public int num_r; // number of flight
      public int place; // place
      public string date_v; // flight date
      public string punkt_pr; // destination
      public string data_pr; // arrival date
      public int time_pr; // arrival time
      public double price; // цена
      public string time_prod; // the time of ticket sales
    }

    public Form1()
    {
      InitializeComponent();
    }
  }
}

 

5. Classes Dictionary<Key, Value> and List<T>. Description of the basic data structures.

According to the task, data, that are placed into the files “Flight.txt” and “Tickets.txt” are formed in the collections.

The collection of type “dictionary” (Dictionary) is provided as “key-value“. The value of a key is unique.

For the “Flight” structure is advisable to form data in the form of a dictionary or an associative array. This is due to the fact that number of flight in the list of flights, is unique (cannot repeated).

In C# to provide the collection of type “dictionary” (associated array) are implemented two base classes:

  • class HashTable – belongs to the generic collections;
  • class Dictionary – belongs to the generic collections.

According to the task, you need to use the class Dictionary.

To provide the associative array into the text of form class, you need to enter the object with name avia, that is of type Dictionary<int, Flight>:

// Associated array of structures Flight
Dictionary<int, Flight> avia = new Dictionary<int, Flight>();

In this description, the type int is the flight number. But type “Flight” is the structure, which corresponds to this flight.

For the different flights the tickets numbers can be repeated. Therefore is convenient to realize tickets as a generic dynamic array of type List<T>. Instead, type <T> is substituted Tickets structure – as a result is obtained List <Tickets>.

Enter the object tickets:

// dynamic array (list) of structures "Tickets"
List<Tickets> tickets = new List<Tickets>();

 

6. Connecting of the System.IO namespace. Class StreamReader.

According to the task, in the program is realized the reading from file. .NET Framework class library is a set of tools for interaction between program and files (open file, read file etc).

In this paper we used StreamReader class capabilities. This class is described in the namespace System.IO. So, at the beginning of the file “Form1.cs“, enter the line:

using System.IO;

StreamReader class is designed for entering characters from the byte stream. To output the symbol into the byte stream is used class “StreamWriter“.

Class StreamReader includes method ReadLine(), that reads a text string from the file. Method ReadLine() returns the string. This method will be used in this task for reading the file.

 

7. Programming the methods of reading data from files “Flight.txt” and “Tickets.txt“.

Data, that were read from files “Flight.txt” and “Tickets.txt“, are displayed in controls listBox1 and listBox2. To displaying the data you need to create two methods. First method Read_Avia() executes the following operations:

  • reads the list of flights from file “Flight.txt“;
  • forms the associate array avia of type Dictionary<int, Flight>;
  • forms the list of flights into the listBox1 for it displaying on the form.

Second method Read_Tickets() executes the following operations:

  • reads the list of purchased tickets from file “Tickets.txt“;
  • forms the dynamic array tickets of type List<Tickets>;
  • displays the content of the file “Tickets.txt” in listBox2.

Listing of methods Read_Avia() and Read_Tickets() is following:

public void Read_Avia()
{
  StreamReader sr = new StreamReader("Flight.txt", Encoding.Default);
  string s = "";
  string[] fields;
  Flight sa; // additional variable - structure of type "Flight"

  // Basic loop.
  // In the loop:
  // 1. Reading data from file "Flight.txt"
  // 2. Forming the dictionary avia of type Dictionary<int, Flight>
  while (s != null)
  {
    s = sr.ReadLine(); // reading the string from the file
    if (s != null)
    {
      fields = s.Split(',');

      // forming the structure sa of type struct Flight
      sa.num_r = Convert.ToInt32(fields[0]);
      sa.punkt_vd = fields[1];
      sa.time_v = Convert.ToInt32(fields[2]);
      sa.n_places = Convert.ToInt32(fields[3]);

      // add pair <num_r, sa> into the dictionary avia
      // the key to the structure is the num_r flight number
      avia.Add(sa.num_r, sa);

      // add the string s into listBox1
      listBox1.Items.Add(s);
    }
  }
}


public void Read_Tickets()
{
  StreamReader sr = new StreamReader("Tickets.txt", Encoding.Default);
  string s;
  string[] fields; // array of strings-fields of the structure Tickets
  Tickets tk; // additional variable - structure of type "Flight"

  s = sr.ReadLine();

  // Basic loop.
  // In the loop:
  // 1. Reading data from file "Tickets.txt"
  // 2. Forming the list tickets of type List<Tickets>

  // we use the loop do...while()
  do
  {
    // divide the string s into pieces on the basis of the character ','
    fields = s.Split(',');

    // fill the structure tk
    tk.num_t = Convert.ToInt32(fields[0]);
    tk.num_r = Convert.ToInt32(fields[1]);
    tk.place = Convert.ToInt32(fields[2]);
    tk.date_v = fields[3];
    tk.punkt_pr = fields[4];
    tk.data_pr = fields[5];
    tk.time_pr = Convert.ToInt32(fields[6]);
    tk.price = Convert.ToDouble(fields[7]);
    tk.time_prod = fields[8];

    // add the structure tk into the list tickets
    tickets.Add(tk);
 
    listBox2.Items.Add(s);
    s = sr.ReadLine();
  }
  while (s != null);
}

Let’s explain some code snippets in the methods Read_Avia() and Read_Tickets().

Reading of file is realized by using class StreamReader, which is assigned for entering the characters from the byte stream. Opening the files is realized in the constructor of class StreamReader:

StreamReader sr = new StreamReader("Flight.txt", Encoding.Default);
StreamReader sr = new StreamReader("Tickets.txt", Encoding.Default);

Reading the string from the file is realized by using method ReadLine() of class StreamReader. If the end of the file, method returns null.

By using a string

fields = s.Split(',');

is realized the separation of string at the parts. Symbol ‘ , ‘ (comma) is the separator between parts.

String

avia.Add(sa.num_r, sa);

adds the number of flight and structure sa into the collection avia of Dictionary<int, Flight> type.

String

tickets.Add(tk);

adds the structure tk into the collection of type List<Tickets>.

 

8. Code changing the constructor of form Form1().

Methods Read_Avia() and Read_Tickets() are placed into the constructor of form Form1().

Listing of constructor of form Form1 is following:

public Form1()
{
    InitializeComponent();
    Read_Avia();
    Read_Tickets();
}

 

9. Programming the event of click on the button “Calculate“.

Listing of event handler of clicking on the button “Calculate” is following:

private void button1_Click(object sender, EventArgs e)
{
  // Calculation
  // 1. Flights with a maximum flight duration
  int i, j;
  int max, tmp;
  bool f_first = true;
 
  max = 0;

  foreach (var a in avia)
  {
    foreach (var t in tickets)
      if (a.Value.num_r == t.num_r)
      {
        if (f_first)
        {
          max = t.time_pr - a.Value.time_v;
          f_first = false;
        }
        else
        {
          tmp = t.time_pr - a.Value.time_v;
          if (max < tmp) max = tmp;
        }
      }
  } // the maximum duration of the flight in the variable max

  // forming the list of flights with the maximum duration of the flight
  listBox3.Items.Clear();
  foreach (var a in avia)
  {
    foreach (var t in tickets)
      if (a.Value.num_r == t.num_r)
      {
        tmp = t.time_pr - a.Value.time_v;
        if (tmp == max)
        {
          string s;
          s = a.Value.num_r.ToString() + ", " +
              a.Value.punkt_vd + ", " +
              a.Value.time_v.ToString() + ", " +
              a.Value.n_places.ToString() + " - " +
              t.num_t.ToString() + ", " +
              t.punkt_pr + ", " +
              t.time_pr.ToString() + ", " +
              t.place.ToString();
          listBox3.Items.Add(s);
        }
      }
  }

  label4.Text = "Flights with the maximum duration of the flight: " + max.ToString();
  // 2. The number of passengers who are waiting for the departure:
  int tm, k;
  tm = Int32.Parse(textBox1.Text); // get time
  k = 0; // number of passengers
  foreach (var a in avia)
  {
    foreach (var t in tickets)
      if ((a.Value.num_r == t.num_r)&&(tm==a.Value.time_v))
        k++;
  }
  label5.Text = "The number of passengers, who are waiting for the departure: " + k.ToString();
}

In the above listing we should note. When viewing the collections used foreach statement (and only foreach). The foreach statement is used for referring to the elements of collection in the loop, which is a group of objects. Using other loop statements is error. The list of flights with a maximum flight duration is displayed in the listBox3 control.

 

10. Run the application.

The result of running the application is shown in Figure 3.

C# - Windows Forms. Program executingFig. 3. The result of running the application