C# 遍历没有特定类型的IQueryable?

C# 遍历没有特定类型的IQueryable?,c#,anonymous-types,C#,Anonymous Types,所以我有一个LINQ查询,它以一个自定义的select结束,类似这样: select new { this1 = table.this1, this2 = othertable.this2 } ViewData["these"] = theRepo.GetAllThese(someVar, anotherVar); select new FoobarViewModel { foo = table.this1, bar = othertable.this2 } 控制器对该查询的调用如下所示:

所以我有一个LINQ查询,它以一个自定义的select结束,类似这样:

select new { this1 = table.this1, this2 = othertable.this2 }
ViewData["these"] = theRepo.GetAllThese(someVar, anotherVar);
select new FoobarViewModel { foo = table.this1, bar = othertable.this2 }
控制器对该查询的调用如下所示:

select new { this1 = table.this1, this2 = othertable.this2 }
ViewData["these"] = theRepo.GetAllThese(someVar, anotherVar);
select new FoobarViewModel { foo = table.this1, bar = othertable.this2 }
现在,当我把它传递给我的视图时,因为它不是强类型的,我如何用foreach遍历它,如果我不知道其中包含什么,我如何将它转换为IQueryable或List

…是这样的吗

IQueryable<???> these = ViewData["These"];
foreach (var this in these) {...

我想您只需要知道为“?”放什么。

您不能在定义它的范围之外使用匿名类型select new{Property=value}。因此,您应该在{yourQueryHere}中使用foreachvar x,它位于您在其中定义查询的方法中

例如: 这是可能的:

    public void myMethod() {
        var x = from c in IEnumerable select new { Prop = value };
        foreach (var y in x) {
        }
    }
这是不可能的:

    public void myMethod() {
        var x = from c in IEnumerable select new { Prop = value };
        foreach (var y in x) {
        }
    }
    public void myMethod() {
        foreach (var y in myMethod2()) {
        }
    }

    public IQueryable<???> myMethod2() {
        return from c in IEnumerable select new { Prop = value };
    }

linq查询返回匿名类型化对象的集合。由于匿名,在声明显式类型化变量时无法调用它们的名称。因此,对象的真实类型/形状仅在定义对象的操作方法中已知

ViewData对象的索引getter具有对象的返回类型,并且在不知道类型名称的情况下,您希望能够将ViewData的返回值[这些]强制转换为任何有用的值

您可能想做的是创建一个模型,更具体地说是一个模型,它定义了您正在使用LINQ选择的对象的结构:

public class FoobarViewModel
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}
并重新定义查询以执行如下选择:

select new { this1 = table.this1, this2 = othertable.this2 }
ViewData["these"] = theRepo.GetAllThese(someVar, anotherVar);
select new FoobarViewModel { foo = table.this1, bar = othertable.this2 }

您的对象现在共享一个通用的命名类,您的集合可以轻松地在视图中转换为正确的类型。

var永远不能是返回类型:GetAllThis的返回类型是什么?@Webleeuw,这很好:公共字符串GetFoo{var x=foo;return x;}