位置:首頁 > 其他技術 > LinQ教學 > LINQ相等

LINQ相等

比較兩個句子(枚舉),並確定它們是精確匹配與否。

 
操作 描述 C#查詢表達式語法 VB查詢表達式語法
SequenceEqual 結果是一個布爾值,如果兩個序列被發現是彼此相同 不適用 不適用

SequenceEqual例子 - Enumerable.SequenceEqual方法

C#

using System;
using System.Collections.Generic;
using System.Linq;

namespace Operators
{
  class SequenceEqual
  {
     static void Main(string[] args)
     {
        Pet barley = new Pet() { Name = "Barley", Age = 4 };
        Pet boots = new Pet() { Name = "Boots", Age = 1 };
        Pet whiskers = new Pet() { Name = "Whiskers", Age = 6 };

        List<Pet> pets1 = new List<Pet>() { barley, boots };
        List<Pet> pets2 = new List<Pet>() { barley, boots };
        List<Pet> pets3 = new List<Pet>() { barley, boots, whiskers };

        bool equal = pets1.SequenceEqual(pets2);
        bool equal3 = pets1.SequenceEqual(pets3);

        Console.WriteLine("The lists pets1 and pets2 {0} equal.", equal ? "are" :"are not");
        Console.WriteLine("The lists pets1 and pets3 {0} equal.", equal3 ? "are" :"are not");

        Console.WriteLine("\nPress any key to continue.");
        Console.ReadKey();
     }

     class Pet
     {
        public string Name { get; set; }
        public int Age { get; set; }
     }
  }
}

VB

Module Module1
  Sub Main()

     Dim barley As New Pet With {.Name = "Barley", .Age = 4}
     Dim boots As New Pet With {.Name = "Boots", .Age = 1}
     Dim whiskers As New Pet With {.Name = "Whiskers", .Age = 6}

     Dim pets1 As New System.Collections.Generic.List(Of Pet)(New Pet() {barley, boots})
     Dim pets2 As New System.Collections.Generic.List(Of Pet)(New Pet() {barley, boots})
     Dim pets3 As New System.Collections.Generic.List(Of Pet)(New Pet() {barley, boots, whiskers})

     Dim equal As Boolean = pets1.SequenceEqual(pets2)
     Dim equal3 As Boolean = pets1.SequenceEqual(pets3)

     Console.WriteLine("The lists pets1 and pets2 {0} equal.", IIf(equal, "are", "are not"))
     Console.WriteLine("The lists pets1 and pets3 {0} equal.", IIf(equal3, "are", "are not"))

     Console.WriteLine(vbLf & "Press any key to continue.")
     Console.ReadKey()
  End Sub

  Class Pet
     Public Property Name As String
     Public Property Age As Integer
  End Class
End Module

當C#或VB的上述代碼被編譯和執行時,它產生了以下結果:

The lists pets1 and pets2 are equal.
The lists pets1 and pets3 are not equal.

Press any key to continue.