Trong bài viết này mình sẽ giới thiệu một số kỹ thuật thao tác với List Collection trong VB.Net:
1. Một số kỹ thuật lấy data cho một list collection
1. Một số kỹ thuật lấy data cho một list collection
Bên dưới là code example trình bày cách lấy data có value là 1 từ một data có sẵn cho list collection.
Module MinhHoangBlog Sub Main() Dim listID As New List(Of String) ' Declaration of list Dim listID1 As New List(Of String) Dim listID2 As New List(Of String) Dim dictionaryID As New Dictionary(Of String, Integer) ' Declaration of dictionary ' Put key and value to dictionary dictionaryID.Add("first", 1) dictionaryID.Add("second", 2) dictionaryID.Add("first1", 1) ' ① Using LINQ ' Reset Data of list If listID IsNot Nothing Then listID.Clear() End If ' Get list Key of map data that have Value = 1 listID = (From kp As KeyValuePair(Of String, Integer) In dictionaryID Where kp.Value = 1 Select kp.Key).ToList() ' Print data of list For Each item In listID Console.WriteLine(" " & item) Next Console.WriteLine( " " & "==========" ) ' ② Using If with For Each pair In dictionaryID ' Khai báo biến lưu trữ cặp Key-Value cua map Dim pair As KeyValuePair(Of String, Integer) ' Reset data of list listID1.Clear() ' Get list Key of map data that have Value = 1 For Each pair In dictionaryID If pair.Value = 1 Then listID1.Add(pair.Key) End If Next ' Print data of list For Each item In listID1 Console.WriteLine(" " & item) Next Console.WriteLine( " " & "==========" ) ' ③ Using Lamba Expression ' Reset data of list listID2.Clear() ' Get list Key of map data that have Value = 1 listID2 = dictionaryID.Where(Function(n) n.Value = 1).Select(Function(n) n.Key).ToList() ' Print data of list For Each item In listID2 Console.WriteLine(" " & item) Next Console.ReadKey() End Sub End Module

Kết quả chương trình