在select语句中使用命名元组 [英] Using named tuples in select statements

查看:118
本文介绍了在select语句中使用命名元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#7中,是否有使用var目标变量选择命名元组的更好方法?在示例1中,我一定做错了什么,或者完全误解了.我似乎必须显式设置目标类型才能做到这一点.

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)));

推荐答案

您可以只使用var,但是您需要确保元组元素实际上已命名.

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

在C#7.0中,您需要明确地执行此操作:

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}");
}

在C#7.1中,当从属性或字段中获取元组文字中的值时,该标识符将隐式为元素名称,因此您可以编写:

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.

这篇关于在select语句中使用命名元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆