LINQ级联


进行两个序列的串联,是比较相似联合操作在其操作,但这不会删除重复记录。

操作 描述 C#查询表达式语法 VB查询表达式语法
Concat 两个序列被连接为一个单一的一个序列的形成。 不适用 不适用

Concat例子 - Enumerable.Concat(Tsource)方法

C#

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

namespace Operators
{
  class Concat
  {
     static void Main(string[] args)
     {
        Pet[] cats = GetCats();
        Pet[] dogs = GetDogs();

        IEnumerable<string> query = cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name));

        foreach (var e in query)
        {
           Console.WriteLine("Name = {0} ", e);
        }

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

     static Pet[] GetCats()
     {
        Pet[] cats = { new Pet { Name="Barley", Age=8 },
                       new Pet { Name="Boots", Age=4 },
                       new Pet { Name="Whiskers", Age=1 } };
                     return cats;
     }

     static Pet[] GetDogs()
     {
        Pet[] dogs = { new Pet { Name="Bounder", Age=3 },
                       new Pet { Name="Snoopy", Age=14 },
                       new Pet { Name="Fido", Age=9 } };
                     return dogs;
     }
  }

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

VB

Module Module1

  Sub Main()

     Dim cats As List(Of Pet) = GetCats()
     Dim dogs As List(Of Pet) = GetDogs()

     Dim list = cats.Cast(Of Pet)().Concat(dogs.Cast(Of Pet)()).ToList()

     For Each e In list
        Console.WriteLine("Name = {0}", e.Name)
     Next

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

  Function GetCats() As List(Of Pet)

     Dim cats As New List(Of Pet)

        cats.Add(New Pet With {.Name = "Barley", .Age = 8})
        cats.Add(New Pet With {.Name = "Boots", .Age = 4})
        cats.Add(New Pet With {.Name = "Whiskers", .Age = 1})

        Return cats
  End Function

  Function GetDogs() As List(Of Pet)

     Dim dogs As New List(Of Pet)

        dogs.Add(New Pet With {.Name = "Bounder", .Age = 3})
        dogs.Add(New Pet With {.Name = "Snoopy", .Age = 14})
        dogs.Add(New Pet With {.Name = "Fido", .Age = 9})

        Return dogs
  End Function

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

当在C#或VB上面的代码被编译和执行时,它产生了以下结果:

Barley 
Boots 
Whiskers 
Bounder 
Snoopy 
Fido

Press any key to continue.

上一篇: LINQ转换操作 下一篇: LINQ聚合