在select语句中声明显式类型而不是var [英] Declaring explicit type instead of var in select statement

查看:41
本文介绍了在select语句中声明显式类型而不是var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行以下请求.它按预期工作并返回正确构造的数据.(它将创建一个具有与公共字段相对应的"head"的元素,并将该字段中具有相同值的所有元素作为一个数组放入"tail"中.)

I'm doing the following request. It works as supposed to and returns data structured correctly. (It creates an element with "head" corresponding to the common field and puts the all elements of the same value in that field as a an Array in the "tail".)

var result
  = from A in As
    group A by A.F into B
    select new 
    {
      F1 = B.Key,
      F2 = from A in As
           where A.F == B.Key
           select A
    };

现在,我想显式声明它的类型.我已经在调试器中检查了我对类型的假设是正确的,但是,当我尝试声明它时,它给了我转换错误.

Now I'd like to declare it's type explicitly. I've checked in the debugger that my assumption on types is correct, however, when I try to declare that, it gives me conversion errors.

  1. 为什么?
  2. 如何显式声明类型?

我尝试了不同的声明和 as 变体,但失败了.

I've tried different variant of declarations and as but failed.

IEnumerable<Tuple<String, IEnumerable<MyType>>> result 
  = from ...
    } as Tuple<String, MyType>;

我知道这是可行的,但是我缺乏使它正确的经验.我注意到以下作品.但是,我不确定如何更进一步,将 Object 替换为实际的变量类型.

I know it's doable but I lack the experience to get it right. I've noticed that the following works. However, I'm not sure how to take it a step further, exchanging Object for the actual variable type.

IEnumerable<Object> result 
  = from ...
    } as Object;

推荐答案

尽管您知道对象"insides"是相同的,但是C#是静态类型的,并根据其元数据(名称,名称空间...)解析类型,不在他们的成员上.您选择一个匿名类型,而不是 Tuple ,因此类型解析器不能同意"它用作 Tuple .

Although you know that the object "insides" are the same, C# is statically typed and resolves types based on their metadata (name, namespace...), not on their members. You select an anonymous type, not a Tuple, so the type resolver cannot "agree" with it being used as a Tuple.

如果您将鼠标悬停在Visual Studio中的 var 关键字上,它将告诉您它的类型(因为在编译时必须知道它,除非它是动态的 ).但是,由于您使用的是匿名类型,因此您将无法显式地编写该类型-C#源代码中没有名称.

If you hover over the var keyword in Visual Studio, it will tell you what type is it (because it must be known during compile time, unless it's a dynamic). However due to the fact you are using anonymous type, you will not be able to write the type explicitly - it has no name in the C# source code.

您可能会在其他地方定义类型

What you might do is either define the type elsewhere

internal class MyObj
{
    public MyObj(string head, IEnumerable<Foo> tail)
    {
        Head = head;
        Tail = tail;
    }

    public string Head { get; set; }
    public IEnumerable<Foo> Tail { get; set; }
}

,然后在查询中使用它:

and then use it in your query:

IEnumerable<MyObj> result
  = from A in As
    group A by A.F into B
    select new MyObj(
        B.Key,
        from A in As
        where A.F == B.Key
        select A);

或按照Jon的建议 此处 使用 Tuple .

or use a Tuple as Jon suggested here.

这篇关于在select语句中声明显式类型而不是var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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