How to use the Join () extension method?

I can understand the line .Join ()

  var stringies1 =new [] {"Blood", "is", "Thicker", "Than", "Water" };
  var zoin = string.Join("|", stringies1);

How is it different from the Join () extension method?

I mean stringies1.Join(IEnumerable<T Result......)

+3
source share
3 answers

The extension method you are referencing is Enumerable.Join, designed to combine collections, which means that you place them side by side and try to match elements with elements, creating results. Think of it as matching a phone book with your list of party names to find a phone number for all the names that you have on your list.

So, no, the Join extension method cannot be used to place them one array one after another and combine them into one long array.

, Enumerable.Concat .

/ , , IEnumerable<T>, , , IEnumerable<T> . Enumerable.ToArray.

, :

var stringies1 = new [] {"Blood", "is", "Thicker", "Than", "Water" };
var stringies2 = new [] { "and", "so", "is", "wine" };

var stringies3 = stringies1.Concat(stringies2).ToArray();
// stringies3 now contains "Blood", "is", ... and "and", "so", "is", ...

, .NET 3.5 :

using System.Linq;

, , ( - , ) .NET 3.5, - . ( .NET 2.0), :

public static T[] Concat<T>(T[] firstSource, T[] secondSource,
    params T[] restOfSources)
{
    // omitted validation of non-null arguments, etc.

    Int32 totalLength = firstSource.Length + secondSource.Length;
    foreach (T[] source in restOfSources)
        totalLength += source.Length;

    T[] result = new T[totalLength];
    Int32 currentIndex = 0;

    Array.Copy(firstSource, 0, result, currentIndex, firstSource.Length);
    currentIndex += firstSource.Length;

    Array.Copy(secondSource, 0, result, currentIndex, secondSource.Length);
    currentIndex += secondSource.Length;

    foreach (T[] source in restOfSources)
    {
        Array.Copy(source, 0, result, currentIndex, source.Length);
        currentIndex += source.Length;
    }

    return result;
}

:

var stringies1 = ...
var stringies2 = ...

var stringies3 = YourClass.Concat(stringies1, stringies2);
+1

, Enumerable.Join? string.Join IEnumerable.Join - :

+3

The same function of a different approach for readability and less code if necessary.

-1
source

Source: https://habr.com/ru/post/1720761/


All Articles