我正在做下面的请求。它的工作方式应该是正确的,并返回结构正确的数据。(它创建一个与公共字段对应的"head“元素,并将该字段中值相同的所有元素作为数组放在”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
    };现在我想显式地声明它的类型。我在调试器中签入了我对类型的假设是正确的,但是,当我试图声明时,它会给出转换错误。
我尝试过不同的声明和as,但是失败了。
IEnumerable<Tuple<String, IEnumerable<MyType>>> result 
  = from ...
    } as Tuple<String, MyType>;我知道这是可行的,但我缺乏正确的经验。我注意到了以下几点。但是,我不知道如何更进一步,将对象替换为实际的变量类型。
IEnumerable<Object> result 
  = from ...
    } as Object;发布于 2013-01-16 13:07:02
尽管您知道对象“内部”是相同的,但是C#是静态类型的,并且根据它们的元数据(名称、命名空间.)而不是它们的成员来解析类型。您选择的是匿名类型,而不是Tuple,因此类型解析器不能“同意”将其用作Tuple。
如果您悬停在Visual中的var关键字上,它将告诉您它是什么类型(因为它必须在编译时知道,除非它是dynamic)。但是,由于您使用的是匿名类型,您将无法显式地编写该类型--它在C#源代码中没有名称。
您可以做的是在其他地方定义类型。
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; }
}然后在查询中使用它:
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);或者按照乔恩的建议使用Tuple,here。
发布于 2013-01-16 12:58:58
生成的可枚举序列的类型由select子句后的表达式类型确定,因此:
select Tuple.Create(
    B.Key,
    (from A in As where A.F == B.Key select A).ToList()
)发布于 2013-01-16 13:02:58
Tuple<String, IEnumerable<MyType>> <=> Tuple<String, MyType>开始时,但是问题不在这里,您不能将匿名类型转换为Tuple。您必须显式定义类型,然后使用它。
public class YourClass
{
    public string F1 {get; set;}
    public IEnumerable<MyType> F2 {get; set;}
} 
IEnumerable<YourClass> result
  = from A in As
    group A by A.F into B
    select new YourClass
    {
      F1 = B.Key,
      F2 = from A in As
           where A.F == B.Key
           select A
    };https://stackoverflow.com/questions/14359007
复制相似问题