I can understand the string.Join( )
var stringies1 =new [] {"Blood", "is", "Thicker", "Than", "Water" };
var zoin = string.Join("|", stringies1);
How does it differ from e开发者_如何学运维xtension method Join() ?
I mean stringies1.Join(IEnumerable<T Result......)
I assume that by the extension method, you are referring to the Enumerable.Join
method? The string.Join
an IEnumerable.Join are two rather different methods:
string.Join
will take an array of strings, join them together using some separator, and return the resulting string.Enumerable.Join
will act on two collections much in the same way as a JOIN operation in SQL does
The extension method you're referring to, Enumerable.Join is for joining collections, which means you place them up side by side and try to match items against items, producing results. Think of it like matching the phone book with your list of names for a party, to find the phone number for all the names you have on your list.
So, no, the extension method Join can not be used to place them one array after each other and combine them to one long array.
There is an alternative however, you can use the extension method Enumerable.Concat in the same class.
This method does not operate on/with only arrays, but on all collection types that implement IEnumerable<T>
, and will thus also produce another IEnumerable<T>
as its result. This result you can then convert to an array using Enumerable.ToArray.
Thus, you would use the following code:
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", ...
This assumes you're using .NET 3.5 and have the following in the using-list at the top of your file:
using System.Linq;
If, on the other hand, you (or someone else finding this answer) are not using .NET 3.5, you need some manual code. Here's a simple generic method (assumes .NET 2.0) that can help you:
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;
}
This can be used like this:
var stringies1 = ...
var stringies2 = ...
var stringies3 = YourClass.Concat(stringies1, stringies2);
Same function different approach for readability, and less code when appropriate.
精彩评论