peri hokiperihokiclarustologisticsrimashaop.compola taktis menang gates of olympus x1000 perihokipemain perihoki bongkar trik jepep starlight princess x1000perihoki beri panduan lengkap bermain mahjong ways 2 pgsofttips cara penghasil uang pgsoft mahjong ways 2 perihokimahjong wins 3 perihoki memberikan penggali terbesarfenomena gates of olympus buka peluang besar bagi duta76cara dapat pola emas rahasia di duta7 wild west goldtrik menang pgsoft mahjong ways 2 modal receh maxwin duta76duta76 main pgsoft mahjong ways 2 di sela istirahatscatter hitam mahjong wins 3 spin pasti jepe duta76perihoki spin mahjong ways 2 pgsoft scatter hitam maxwinsimbol mahjong wins 3 yang sering muncul di awal perihokitrik gampang menang mahjong winscuan mahjong wins 3 tanpa hentipola spin taruhan kecil mahjong winsstrategi kunci scatter hitam beruntungacor total mahjong wayskemenangan maksimal mahjong wayskemenangan pria pekanbaru mahjong waysmahjong wins3 fenomena baru sumatera baratmenangkan mahjong dengan lincahmenembus batas keberuntungan mahjong waysmenjajal keberuntungan di mahjong wayspola gratis mahjong ways1scatter hitam senjata rahasia mahjong winsteknik spinning menguntungkan untuk scatter hitamanalisis rtp tertinggi mahjong winsfenomena scatter hitam mahjong winsibu rumah tangga dan keberuntungan mahjongkeseruan main mahjong wins3menang mahjong pengguna baru di sosial mediamenghargai setiap momen di mahjong waysserunya main mahjong di warung internetspin slow motion mancing scatterstrategi jitu maxwin mahjong waysstrategi jitu menang mahjong modal kecil jackpot besaranak kampung papua menggemparkan mahjongkeajaiban scatter hitam mahjong wayskeberhasilan joni mahjong winskejaiban mahjong ways di ujung jalanketua mahjong wins3 kehadiran kemenangan dimulai dari balimahjong kehadiran yang menguntungkanmahjong menggila adat88panduan kilat raih 108 jutatips memenangkan mahjongbarista kopi menang 110 juta spin mahjongdakota76 scatter hitam mahjong wins 3gagal cpns menang mahjong wins 3 rp120 jutakisah karyawan minimarket dapat thr lebih awal mahjong winskisah pelajar sma kuasai mahjong wins 3 inspirasi sekolahkisah penjaga parkir tanah abang motor baru mahjong winskisah sukses ibu rumah tangga bandung mahjong winsmahasiswa kkn beli iphone15 mahjong wins3 dakotamantan anak band influencer mahjong scatter hitampola rtp senin gates of olympus guru matematikaidola scatter hitam gampang meledakidola sensasi jackpotidola pola scatter hitamidola hasilkan jackpot dalam waktu singkatidola mahjong wins 3 bocortukang cuci motor menemukan keberuntungan di mahjong

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 282

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_cookie_params(): Cannot change session cookie parameters when headers already sent

Filename: Session/Session.php

Line Number: 294

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 304

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 314

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 315

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 316

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 317

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: Session/Session.php

Line Number: 375

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: ini_set(): Headers already sent. You cannot change the session module's ini settings at this time

Filename: drivers/Session_files_driver.php

Line Number: 108

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_set_save_handler(): Cannot change save handler when headers already sent

Filename: Session/Session.php

Line Number: 110

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: session_start(): Cannot start session when headers already sent

Filename: Session/Session.php

Line Number: 143

Backtrace:

File: /home/blogchuabenh/domains/freetuts.net/public_html/site/controllers/Main_controller.php
Line: 10
Function: __construct

File: /home/blogchuabenh/domains/freetuts.net/public_html/sources/index.php
Line: 299
Function: require_once

File: /home/blogchuabenh/domains/freetuts.net/public_html/index.php
Line: 26
Function: require_once

Cách dùng Dictionary trong C# - Freetuts
CĂN BẢN
NÂNG CAO
CÁC CHỦ ĐỀ
BÀI MỚI NHẤT
MỚI CẬP NHẬT

Cách dùng Dictionary trong C#

Trong bài viết này chúng ta sẽ tìm hiểu về Dictionary trong C#. Dictionary được sử dụng để lưu trữ các cặp key/value không theo thứ tự sắp xếp cụ thể.

test php

banquyen png
Bài viết này được đăng tại freetuts.net, không được copy dưới mọi hình thức.

Mình sẽ giới thiệu về các đặc điểm của Dictionary, cùng với đó là các thao tác với Dictionary trong C#.

1. Các đặc điểm của Dictionary

Dưới đây là một số đặc điểm của Dictionary:

  • Lưu trữ các cặp key/value.
  • Nằm trong System.Collection.Generic namespace.
  • Triển khai giao diện IDictionary.
  • Các key phải là duy nhất và không được để trống.
  • Value có thể trùng lặp và có thể là giá trị null.
  • Các Value có thể được truy cập thông qua key của nó.
  • Các phần tử được lưu trữ dưới dạng KeyValuePair <TKey, TValue>.

2. Tạo Dictionary

Chúng ta có thể tạo một Dictionary bằng cách truyền vào key và value cần lưu trữ. Ví dụ dưới đây là cách tạo một Dictionary và cách thêm các cặp key/value cho nó.

Bài viết này được đăng tại [free tuts .net]

using System;
using System.Collections.Generic;

public class Program
{
   public static void Main()
   {
	IDictionary<int, string> numberNames = new Dictionary<int, string>();
        //sử dụng phương thức Add() đẻ thêm các phần tử cho Dictionary
	numberNames.Add(1,"One"); 
	numberNames.Add(3,"Three");
	numberNames.Add(2,"Two");
	//sử dụng phương thức foreach để in các phần tử ra màn hình
	foreach(KeyValuePair<int, string> kvp in numberNames)
	Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
        Console.WriteLine();

	//khai báo và khởi tạo cho key / value bằng bộ khởi tạo
	var cities = new Dictionary<string, string>(){
	        {"UK","London, Manchester, Birmingham"},
		{"USA","Chicago, New York, Washington"},
		{"India","Mumbai, New Delhi, Pune"}
	};
	//sử dụng phương thức foreach để in các phần tử ra màn hình
	foreach(var kvp in cities)
	Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
		
        Console.WriteLine("----------------------------------------");
	Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
    }
}

Trong ví dụ trên numberNames là một Dictionary<int, string> vì vậy nó có thể lưu trữ các key int và value string. Tương tự như vậy ta có cities là một Dictionary<string, string> vì vậy nó có thể lưu trữ key và value ở dạng string.

Dictionary không thể lưu các key trùng lặp hoặc bằng giá trị rỗng, trong khi đó value thì có thể.

Kết quả:

dictionary 01 PNG

3. Truy cập các phần tử trong Dictionary

Dictionary có thể được truy cập bằng cách sử dụng indexer (trình chỉ mục) để chỉ đinh một key liên kết với value.

Ta có thể sử dụng phương thức ElementAt() để lấy KeyValuePair từ chỉ mục được chỉ định.

Ví dụ:

using System;
using System.Linq;
using System.Collections.Generic;		
public class Program
{
   public static void Main()
   {
        //khai báo và khởi tạo một Dictionary
        var cities = new Dictionary<string, string>(){
	    {"UK", "London, Manchester, Birmingham"},
	    {"USA", "Chicago, New York, Washington"},
	    {"India", "Mumbai, New Delhi, Pune"}
        };

	Console.WriteLine("---Các phần tử trong Dictionary---");
	//sử dụng phương thức ElementAt() để truy cập vào Dictionary
	for (int i = 0; i < cities.Count; i++)
	{
	    Console.WriteLine("Key: {0}, Value: {1}", 
	    cities.ElementAt(i).Key, 
	    cities.ElementAt(i).Value);
	}

        Console.WriteLine("----------------------------------------");
        Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
    }
}

Kết quả:

dictionary 02 PNG

4. Cập nhật Dictionary

Cập nhật value của một key bằng cách chỉ định một key trong indexer (trình chỉ mục). Trước khi cập nhật ta nên kiểm tra key có tồn tại hay không bằng phương thức ContainsKey().

using System;
using System.Linq;
using System.Collections.Generic;
					
public class Program
{
   public static void Main()
   {
        //khai báo và khởi tạo một Dictionary
	var cities = new Dictionary<string, string>(){
	    {"UK", "London, Manchester, Birmingham"},
	    {"USA", "Chicago, New York, Washington"},
	    {"India", "Mumbai, New Delhi, Pune"}
        };
        Console.WriteLine("\n-----------------Dictionary ban đầu----------------------");
        foreach(var kvp in cities)
	Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);

        cities["UK"] = "Liverpool, Bristol";
	cities["USA"] = "Los Angeles, Boston";

	if(cities.ContainsKey("France")){
	    cities["France"] = "Paris";
	}
	Console.WriteLine("\n-----------------Dictionary sau khi cập nhật----------------------");
	foreach(var kvp in cities)
	    Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);

        Console.WriteLine("----------------------------------------");
        Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
    }
}

Kết quả:

dictionary 03 PNG

5. Xóa các phần tử trong Dictionary

Để xóa các cặp key/value trong Dictionary ta có hai phương thức. Phương thức Remove() để xóa một cặp key/value và phương thức Clear() để xóa tất cả các cặp key/value.

using System;
using System.Collections.Generic;
					
public class Program
{
    public static void Main()
    {
        var cities = new Dictionary<string, string>(){
	    {"UK", "London, Manchester, Birmingham"},
	    {"USA", "Chicago, New York, Washington"},
	    {"India", "Mumbai, New Delhi, Pune"}
	};
        foreach(var kvp in cities)
	    Console.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
        //đếm số phần tử lần 1
	Console.WriteLine("\nTổng các phần tử: {0}", cities.Count);

	//sử dụng phương thức Remove() để xóa một cặp key/value
	cities.Remove("UK"); 
        //sử dụng phương thức ContainsKey() để kiểm tra xem key "France" có tồn tại hay không
        //nếu có thì xóa, nếu không thì không xóa
	if(cities.ContainsKey("France")){
	    cities.Remove("France");
	}
	//đếm số phần tử lần 2
	Console.WriteLine("Tổng các phần tử sau khi xóa một phần tử: {0}", cities.Count);

        //sử dụng phương thức Clear() để xóa toàn bộ các phần tử
	cities.Clear(); //deletes all elements
	//đếm lần 3
	Console.WriteLine("Tổng các phần tử sau khi xóa hết: {0}", cities.Count);

        Console.WriteLine("----------------------------------------");
        Console.WriteLine("Chương trình này được đăng tại Freetuts.net");
    }
}

Kết quả:

dictionary 04 PNG

6. Kết luận

Như vậy là chúng ta đã tìm hiểu xong về Dictionary là gì? các đặc điểm của nó, cùng với đó là các thao tác với Dictionary trong C#. Các bạn hãy luyện tập thật nhiều để sử dụng nó thành thạo nhé !!!

Cùng chuyên mục:

Memento Design Pattern trong C# - Cách triển khai và ví dụ

Memento Design Pattern trong C# - Cách triển khai và ví dụ

Interpreter Design Pattern trong C# - Cách triển khai và ví dụ

Interpreter Design Pattern trong C# - Cách triển khai và ví dụ

Strategy Design Pattern trong C# - Cách triển khai và ví dụ

Strategy Design Pattern trong C# - Cách triển khai và ví dụ

Visitor Design Pattern trong C# - Cách triển khai và ví dụ

Visitor Design Pattern trong C# - Cách triển khai và ví dụ

Command Design Pattern trong C# - Cách triển khai và ví dụ

Command Design Pattern trong C# - Cách triển khai và ví dụ

Observer Design Pattern trong C# - Cách triển khai và ví dụ

Observer Design Pattern trong C# - Cách triển khai và ví dụ

Iterator Design Pattern trong C# - Cách triển khai và ví dụ

Iterator Design Pattern trong C# - Cách triển khai và ví dụ

Proxy Design Pattern trong C# - Cách triển khai và ví dụ

Proxy Design Pattern trong C# - Cách triển khai và ví dụ

Composite Design Pattern trong C# - Cách triển khai và ví dụ

Composite Design Pattern trong C# - Cách triển khai và ví dụ

Bridge Design Pattern trong C# - Cách triển khai và ví dụ

Bridge Design Pattern trong C# - Cách triển khai và ví dụ

Decorator Design Pattern trong C# - Cách triển khai và ví dụ

Decorator Design Pattern trong C# - Cách triển khai và ví dụ

Facade Design Pattern trong C# - Cách triển khai và ví dụ

Facade Design Pattern trong C# - Cách triển khai và ví dụ

Adapter Design Pattern trong C# - Cách triển khai và ví dụ

Adapter Design Pattern trong C# - Cách triển khai và ví dụ

Singleton Design Pattern trong C# - Cách triển khai và ví dụ

Singleton Design Pattern trong C# - Cách triển khai và ví dụ

Prototype Design Pattern trong C# - Cách triển khai và ví dụ

Prototype Design Pattern trong C# - Cách triển khai và ví dụ

Builder Design Pattern trong C# - Cách triển khai và ví dụ

Builder Design Pattern trong C# - Cách triển khai và ví dụ

Tự viết ứng dụng quản lý xe ra vào C# Winforms và Firebase

Tự viết ứng dụng quản lý xe ra vào C# Winforms và Firebase

Trong bài viết này Freetuts chia sẽ cho các bạn một ứng dụng khá thú…

Factory Design Pattern trong C# - Cách triển khai và ví dụ

Factory Design Pattern trong C# - Cách triển khai và ví dụ

Chúng ta sẽ tìm hiểu về Factory Design Pattern trong C# là gì? Cách triển…

Hướng dẫn giải phương trình bậc hai trong C#

Hướng dẫn giải phương trình bậc hai trong C#

Giải phương trình bậc nhất ax + b = 0 trong C#

Giải phương trình bậc nhất ax + b = 0 trong C#

Top