Is it possible to write a C# method that accepts a value tuple with any number of items of the same type and converts them into a list?
Edit 2/6/2019 I accepted the Provided answer as the correct one. I wanted to also provide a solution that uses a base class that is not an interface, becuase I am trying to write a conversion operator and user defined conversions from an interface are not allowed.
public static class TupleExtensions
{
public static IEnumerable<object> Enumerate(this ValueType tpl)
{
var ivt = tpl as ITuple;
if (ivt == null) yield break;
for (int i = 0; i < ivt.Length; i++)
{
yield return ivt[i];
}
}
}
Compared to C, C++ has significantly more libraries and functions to use. If you're working with complex software, C++ is a better fit because you have more libraries to rely on. Thinking practically, having knowledge of C++ is often a requirement for a variety of programming roles.
C/C++ is still powering the world despite number of new high level programming languages. Most of the major software applications including Adobe, Google, Mozilla, Oracle are all written in C/C++. There is a complete article on list of best applications written in C/C++.
It was based on CPL (Combined Programming Language), which had been first condensed into the B programming language—a stripped-down computer programming language—created in 1969–70 by Ken Thompson, an American computer scientist and a colleague of Ritchie.
You can use the fact that ValueTuples implement the ITuple interface.
The only issue is that tuple elements can be of arbitrary type, so the list must accept any kind of type.
public List<object> TupleToList(ITuple tuple)
{
var result = new List<object>(tuple.Length);
for (int i = 0; i < tuple.Length; i++)
{
result.Add(tuple[i]);
}
return result;
}
This also works as an extension method:
public static class ValueTupleExtensions
{
public static List<object> ToList(this ITuple tuple)
{
var result = new List<object>(tuple.Length);
for (int i = 0; i < tuple.Length; i++)
{
result.Add(tuple[i]);
}
return result;
}
}
This way it is possible to write var list = (123, "Text").ToList();
.
Edit 2020-06-18: If every element of the tuple is of the same type it's possible to create list with the proper element type:
public List<T> TupleToList<T>(ITuple tuple)
{
var result = new List<T>(tuple.Length);
for (int i = 0; i < tuple.Length; i++)
{
result.Add((T)tuple[i]);
}
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With