Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using named tuples in select statements

Tags:

Is there a nicer way to select a named tuple in C# 7 using a var target variable? I must be doing something wrong in example 1, or misunderstanding something completely. I seem to have to explicitly set the target type in order to do this.

//1. Fails to compile with "incorrect number of type parameters" issue. var tuples = source.Select<(int A, int B)>(x => (x.A, x.B));  //2. Compiles IEnumerable<(int A, int B)> tuples = toCheck.Select(x => (x.A, x.B));  //3. Compiles var tuples = new HashSet<(int A, int B)>(source.Select(x => (x.A, x.B))); 
like image 734
gmn Avatar asked Aug 11 '17 09:08

gmn


People also ask

How do I access a named tuple?

You can access the values in a given named tuple using the dot notation and the field names, like in obj. attr .

How do you use a named tuple in Python?

To create a named tuple, import the namedtuple class from the collections module. The constructor takes the name of the named tuple (which is what type() will report), and a string containing the fields names, separated by whitespace. It returns a new namedtuple class for the specified fields.

Are Named tuples iterable?

Since namedtuple is iterable you can use the iterable methods. For example, if you have "coords" as a class instance, you cannot look for what is the max coord.

Are Named tuples immutable?

As a final note, named tuples are immutable which means that their elements cannot be changed in-place. In the article below you can read more about the difference between mutable and immutable object types and how the both server the dynamic typing model of Python.


2 Answers

You can just use var, but you need to make sure the tuple elements are actually named.

In C# 7.0, you need to do this explicitly:

var tuples = source.Select(x => (A: x.A, B: x.B)); foreach (var tuple in tuples) {     Console.WriteLine($"{tuple.A} / {tuple.B}"); } 

In C# 7.1, when the value in a tuple literal is obtained from a property or field, that identifier will implicitly be the element name, so you'll be able to write:

var tuples = source.Select(x => (x.A, x.B)); foreach (var tuple in tuples) {     Console.WriteLine($"{tuple.A} / {tuple.B}"); } 

See the feature document for more details around compatibility etc.

like image 93
Jon Skeet Avatar answered Sep 28 '22 14:09

Jon Skeet


Select takes 2 type parameters: Select<TSource, TResult>. A tuple (int A, int B) is only one type, you can write it also ValueTuple<int, int>. So you have to write both parameters if you want a named tuple

var tuples = source.Select<TypeOfSource, (int A, int B)>(x => (x.A, x.B)); 
like image 30
Jakub Dąbek Avatar answered Sep 28 '22 14:09

Jakub Dąbek