Menyusun dalam C#

PHPz
Lepaskan: 2024-09-03 15:24:11
asal
297 orang telah melayarinya

Isih dalam c# ialah proses menyusun kandungan koleksi dalam susunan tertentu. Koleksi mungkin tatasusunan, senarai atau mana-mana kumpulan data lain. Koleksi mungkin mengandungi unsur jenis mudah dan juga jenis kompleks. Jenis ringkas mungkin koleksi integer, rentetan, nombor titik terapung, dsb. Jenis kompleks mungkin koleksi objek jenis yang ditentukan pengguna seperti Pekerja, Pelajar, dsb. Jenis kompleks lebih kerap bersarang, bermakna objek mungkin mempunyai berbilang atribut.

Contoh

  • Jenis Mudah
    • Koleksi integer – {1, 2, 3, 4, 5}
    • Koleksi rentetan – {“Mark”, “Jamie”, “Anna”}
  • Jenis Kompleks
    • { [Nama: “Mark”, Id Pekerja: “123”, Pejabat: “London”],
      [Nama: “Jane”, Id Pekerja: “456”, Pejabat: “NY”],
      [Nama: “Annie”, Id Pekerja: “789”, Pejabat: “Sydney”] }

C# telah menyediakan kaedah terbina untuk mengisih koleksi. Sama ada Array, Senarai atau mana-mana Koleksi Generik, kaedah C# Sort() boleh menyusunnya berdasarkan Comparer yang disediakan. Secara dalaman, pelaksanaan .Net menggunakan algoritma Quicksort untuk mengisih koleksi dalam C#. Kami akan membincangkan lebih lanjut mengenai perkara ini dalam bahagian artikel seterusnya.

Bagaimana Pengisihan Dilakukan dalam C#?

Seperti yang dinyatakan sebelum ini, rangka kerja .Net menggunakan pendekatan Quicksort untuk mengisih elemen dalam koleksi C#. Jadi, apakah quicksort?

Quicksort mengikut strategi bahagi dan takluk. Ini bermakna, algoritma pengisihan memilih elemen pangsi dan membahagikan tatasusunan berdasarkan elemen pangsi. Unsur-unsur yang lebih kecil daripada pangsi diletakkan di hadapannya. Unsur-unsur yang lebih besar daripada pangsi diletakkan selepasnya. Ini memastikan elemen pangsi diisih. Juga, tatasusunan dibahagikan kepada dua - elemen yang lebih kecil daripada pangsi dan elemen yang lebih besar daripada pangsi. Seterusnya, algoritma mengikut pendekatan yang sama untuk kedua-dua tatasusunan.

Ilustrasi ini boleh dilihat di bawah.

Susun Tak Isih – 18, 5, 16, 23, 50, 32

Langkah 1 (Pivot = 32) – 18, 5, 16, 23, 32, 50

Langkah 2a
Susun Tak Isih – 18, 5, 16, 23
Pangsi = 23
Tatasusunan Diisih Separa – 18, 5, 16, 23

Langkah 2b
Susun Tak Isih – 50
Pangsi = 50
Tatasusunan Diisih Separa – 50

Langkah 3a
Susun Tak Isih – 18, 5, 16
Pangsi = 16
Tatasusunan Diisih Separa – 5, 16, 18

Susun Isih – 5, 16, 18, 23, 32, 50

Oleh itu, Quicksort mempunyai dua proses utama – memilih pangsi dan membahagikan tatasusunan. Pelaksanaan algoritma bergantung pada pemilihan pangsi. Ia boleh sama ada elemen pertama, atau yang terakhir, atau mana-mana elemen rawak, atau median tatasusunan. Setelah partition selesai dan pivot diletakkan pada kedudukan yang betul, algoritma dipanggil secara rekursif untuk tatasusunan yang dipartisi, sehingga setiap elemen diisih.

Apabila pengisihan dilakukan dalam C#, terdapat konsep Quicksort yang stabil dan tidak stabil. Dalam Quicksort yang stabil, jika dua elemen adalah sama susunannya daripada tatasusunan asal dikekalkan. Jika tidak, ia berada dalam quicksort yang tidak stabil. Pelaksanaan C# menggunakan Quicksort yang tidak stabil.

Jenis Isih dalam C#

Dalam bahagian artikel ini, kami akan memfokuskan terutamanya pada dua jenis koleksi dalam C# – Tatasusunan dan Senarai. Kami akan mendalami cara C# menyusun tatasusunan dan senarai. Bahagian seterusnya akan cuba menerangkannya dengan beberapa contoh.

1. Mengisih Tatasusunan dalam C#

Mari kita lihat cara yang berbeza untuk mengisih tatasusunan dalam C#.

a. Menggunakan Pembanding Lalai

Ini ialah kaedah Isih() lalai. Jika tiada Comparer dihantar secara eksplisit kepada kaedah, C# menggunakan tertib menaik untuk menyusun elemen.

Kod:

using System;
public class Program
{
public static void Main()
{
String[] strArray = {"I", "Am", "Learning", "Array", "Sorting","In", "C#"};
int[] intArray = {23, 76, 12, 43, 90, 30};
Array.Sort(strArray);
Array.Sort(intArray);
Console.WriteLine("Sorted String Array:\n");
DisplayArray(strArray);
Console.WriteLine("\n\n\nSorted Integer Array:\n");
DisplayArray(intArray);
}
static void DisplayArray(string[] arr)
{
foreach (string a in arr)
{
Console.Write(a + "\t");
}
}
static void DisplayArray(int[] arr)
{
foreach (int a in arr)
{
Console.Write(a + "\t");
}
}
}
Salin selepas log masuk

Output:

Menyusun dalam C#

b. Menggunakan Pembanding Tersuai

Kami juga boleh menyediakan Pembanding tersuai kami sendiri kepada kaedah Sort(). Ini akan mengarahkan pengkompil C# untuk menggunakan pembanding tersuai dan bukannya yang lalai.

Untuk mencipta pembanding tersuai, kita perlu melaksanakan kaedah Compare() daripada antara muka IComparer. Kod di bawah menunjukkan cara membuat pembanding yang akan mengisih elemen dalam tertib menurun.

Kami mencipta kelas, mewarisinya daripada antara muka IComparer, melaksanakan kaedah Compare() dan mengatasinya untuk membandingkan elemen dalam tertib menurun.

Kod:

using System;
public class DescendingComparer : System.Collections.IComparer
{
public int Compare(Object a, Object b)
{
return (new System.Collections.CaseInsensitiveComparer()).Compare(b, a);
}
}
public class Program
{
public static void Main()
{
String[] strArray = {"I", "Am", "Learning", "Array", "Sorting","In", "C#"};
int[] intArray = {23, 76, 12, 43, 90, 30};
Array.Sort(strArray, new DescendingComparer());
Array.Sort(intArray, new DescendingComparer());
Console.WriteLine("Sorted String Array in Descending Order:\n");
DisplayArray(strArray);
Console.WriteLine("\n\n\nSorted Integer Array in Desc Order:\n");
DisplayArray(intArray);
}
static void DisplayArray(string[] arr)
{
foreach (string a in arr)
{
Console.Write(a + "\t");
}
}
static void DisplayArray(int[] arr)
{
foreach (int a in arr)
{
Console.Write(a + "\t");
}
}
}
Salin selepas log masuk

Output:

Menyusun dalam C#

c. Using Key-Value Pairs

C# also provides a way to sort one array using key values from another array. The example below has key-value pairs of first names and last names of people. We would sort them by both first and last names using the Sort() method.

Code:

using System;
public class Program
{
public static void Main()
{
String[] firstNames = {"Tom", "Jack", "Anna", "Veronica", "Jessica", "Mike"};
String[] lastNames = {"Phelps", "Anderson", "Spectre", "Clarke",   "Williams", "Fonseca"};
Array.Sort(firstNames, lastNames);
Console.WriteLine("Sorted by First Names:\n");
DisplayArray(firstNames, lastNames);
Array.Sort(lastNames, firstNames);
Console.WriteLine("\n\nSorted by Last Names:\n");
DisplayArray(firstNames, lastNames);
}
static void DisplayArray(string[] arr1, string[] arr2)
{
for (int i = 0; i < arr1.Length; i++)
{
Console.WriteLine(arr1[i] + " " + arr2[i]);
}
}
}
Salin selepas log masuk

Output:

Menyusun dalam C#

2. Sorting a List in C#

Let us look at the different ways in which we can sort a list in C#.

Note – To use Lists in C#, including the library System.Collections.Generic.
a. Using Default Comparer

This is the default sort() method. if no comparer is explicitly passed to the method, c# uses the ascending order to arrange the elements.

Code:

public class Program
using System.Collections.Generic;
{
public static void Main()
{
String[] strArray = {"I", "Am", "Learning", "Array", "Sorting", "In", "C#"};
List<string> strList = new List<string>(strArray);
int[] intArray = {23, 76, 12, 43, 90, 30};
List<int> intList = new List<int>(intArray);
strList.Sort();
intList.Sort();
Console.WriteLine("Sorted String List:\n");
DisplayList(strList);
Console.WriteLine("\n\n\nSorted Integer List:\n");
DisplayList(intList);
}
static void DisplayList(List<string> myList)
{
foreach (string a in myList)
{
Console.Write(a + "\t");
}
}
static void DisplayList(List<int> myList)
{
foreach (int a in myList)
{
Console.Write(a + "\t");
}
}
}
Salin selepas log masuk

Output:

Menyusun dalam C#

b. Using Custom Comparer

We can also provide our own custom comparer to the sort() method. This would instruct the c# compiler to use the custom comparer instead of the default one.

To create a custom comparer, we need to implement the Compare() method from the IComparer interface. The code below demonstrates how to create a comparer that would sort the elements in descending order.

We created a class, inherited it from the IComparer interface, implemented the Compare() method and overrode it to compare the elements in descending order.

Code:

using System;
using System.Collections.Generic;
public class LengthComparer : IComparer<string>
{
public int Compare(string a, string b)
{
return (a.Length.CompareTo(b.Length));
}
}
public class DigitSumComparer : IComparer<int>
{
public int Compare(int a, int b)
{
int sum_a = 0;
int sum_b = 0;
while (a > 0)
{
sum_a += (a % 10);
a /= 10;
}
while (b > 0)
{
sum_b += (b % 10);
b /= 10;
}
return (sum_a.CompareTo(sum_b));
}
}
public class Program
{
public static void Main()
{
LengthComparer lc = new LengthComparer();
DigitSumComparer dsc = new DigitSumComparer();
String[] strArray = {"I", "Am", "Learning", "Array", "Sorting", "In", "C#"};
List<string> strList = new List<string>(strArray);
int[] intArray = {23, 76, 12, 43, 90, 30};
List<int> intList = new List<int>(intArray);
strList.Sort(lc);
intList.Sort(dsc);
Console.WriteLine("Sorted String List by Length:\n");
DisplayList(strList);
Console.WriteLine("\n\n\nSorted Integer List by Sum of Digits:\n");
DisplayList(intList);
}
static void DisplayList(List<string> myList)
{
foreach (string a in myList)
{
Console.Write(a + "\t");
}
}
static void DisplayList(List<int> myList)
{
foreach (int a in myList)
{
Console.Write(a + "\t");
}
}
}
Salin selepas log masuk

Output:

Menyusun dalam C#

Sorting Complex List Types

Complex List Types are user-defined lists. To be more precise, they are lists of objects of user-defined classes. Being user-defined, the objects are a mixture of various primitive types. It is difficult to sort a complex list type. C# compiler expects each complex class to inherit from the IComparable interface and define the method CompareTo(). This method contains the instructions on how to compare the elements of the list for sorting.

In the example below, we define a user-defined class of Employees and sort the Employee objects based on their IDs.

Example #1

Code:

using System;
using System.Collections.Generic;
public class Employee : IComparable<Employee>
{
public int id {get;set;}
public string name{get;set;}
public double salary{get;set;}
public int CompareTo(Employee e)
{
return this.id.CompareTo(e.id);
}
}
public class Program
{
public static void Main()
{
List<Employee> emps = new List<Employee>();
emps.Add(new Employee()
{id = 123, name = "Tom Phelps", salary = 20000.00});
emps.Add(new Employee()
{id = 897, name = "Jack Anderson", salary = 40050.50});
emps.Add(new Employee()
{id = 342, name = "Anna Spectre", salary = 31030.89});
emps.Add(new Employee()
{id = 219, name = "Veronica Clarke", salary = 66333.66});
emps.Add(new Employee()
{id = 642, name = "Jessica Williams", salary = 50505.05});
emps.Add(new Employee()
{id = 923, name = "Mike Fonseca", salary = 76543.21});
Console.WriteLine("Original Employee List:\n");
DisplayList(emps);
emps.Sort();
Console.WriteLine("\n\nSorted Employee List by IDs:\n");
DisplayList(emps);
}
static void DisplayList(List<Employee> emp)
{
foreach (Employee e in emp)
{
Console.WriteLine("Id: " + e.id + ", Name: " + e.name + ",  Salary: " + e.salary);
}
}
}
Salin selepas log masuk

Output:

 Menyusun dalam C#

Now, the obvious question that comes to mind is that what if we want to sort the objects of Employee class based on some other property? This is possible. We would need to implement the IComparer interface. Let us take a look at the example below to understand.

Example #2

Code:

using System;
using System.Collections.Generic;
public class Employee
{
public int id {get;set;}
public string name{get;set;}
public double salary{get;set;}
}
public class SortByName : IComparer<Employee>
{
public int Compare(Employee e1, Employee e2)
{
return e1.name.CompareTo(e2.name);
}
}
public class SortBySalary : IComparer<Employee>
{
public int Compare(Employee e1, Employee e2)
{
return e1.salary.CompareTo(e2.salary);
}
}
public class Program
{
public static void Main()
{
SortByName sbn = new SortByName();
SortBySalary sbs = new SortBySalary();
List<Employee> emps = new List<Employee>();
emps.Add(new Employee()
{id = 123, name = "Tom Phelps", salary = 20000.00});
emps.Add(new Employee()
{id = 897, name = "Jack Anderson", salary = 40050.50});
emps.Add(new Employee()
{id = 342, name = "Anna Spectre", salary = 31030.89});
emps.Add(new Employee()
{id = 219, name = "Veronica Clarke", salary = 66333.66});
emps.Add(new Employee()
{id = 642, name = "Jessica Williams", salary = 50505.05});
emps.Add(new Employee()
{id = 923, name = "Mike Fonseca", salary = 76543.21});
emps.Sort(sbn);
Console.WriteLine("Sorted Employee List by Names:\n");
DisplayList(emps);
emps.Sort(sbs);
Console.WriteLine("\n\nSorted Employee List by Salaries:\n");
DisplayList(emps);
}
static void DisplayList(List<Employee> emp)
{
foreach (Employee e in emp)
{
Console.WriteLine("Id: " + e.id + ", Name: " + e.name + ",  Salary: " + e.salary);
}
}
}
Salin selepas log masuk

Output:

Menyusun dalam C#

Conclusion

So, this article covered in-depth on how to sort collections in C#. We focused majorly on Arrays and Lists since these two covers all the primitive types as well. Once the concept of Sorting in C# is very well understood, it becomes easy to implement sorting in other collections such as Enumerations, Dictionaries, etc. After completing this article, it is recommended to explore the MSDN documentation for more implementations of Sorting in C#.

Atas ialah kandungan terperinci Menyusun dalam C#. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!