TupleExtensions
is a NuGet package with a number of convenience extensions that leverage C# 7 tuples.
This library requires a framework that supports at least version 1.0 of .NET Standard.
Look here to find out if your framework supports it.
Run this in your package manager console:
Install-Package TupleExtensions.VictorGavrish
An extension on the KeyValuePair<TKey, TValue>
struct allows ergonomic
dictionary traversal:
var dictionary = new Dictionary<int, string>
{
{ 1, "one" },
{ 2, "two" }
};
foreach ((var key, var value) in dictionary)
{
Console.WriteLine($"{key}:{value}");
}
Prints:
1:one
2:two
You can await multiple tasks ergonomically:
var task1 = Task.FromResult(1);
var task2 = Task.FromResult(true);
var (val1, val2) = await (task1, task2).WhenAll();
You can do something like this with new and improved Zip
and Unzip
:
var left = new[] { 1, 2, 3 };
var right = new[] { "two", "three", "four" };
var zipped = left.Skip(1).Zip(right);
foreach ((var lval, var rval) in zipped)
{
Console.WriteLine($"{lval}:{rval}");
}
(var newLeft, var newRight) = zipped.Unzip();
foreach (var element in newLeft)
{
Console.WriteLine(element);
}
foreach (var element in newRight)
{
Console.WriteLine(element);
}
This prints:
2:two
3:three
2
3
two
three
WithIndexes
adds indexes to a collection. This allows you to continue to use foreach
where previously you'd be tempted to use a for
loop:
var array = new[] { "one", "two", "three" };
foreach ((var index, var element) in array.WithIndexes())
{
Console.WriteLine($"{index}:{element}");
}
This prints:
0:one
1:two
2:three
You can create a dictionary from a sequence of tuples:
var sequence = new[]
{
(1, "one"),
(2, "two")
};
var dictionary = sequence.ToDictionary();