【问题标题】:How to propagate an anonymous type variable from using scope to outside?如何将匿名类型变量从使用范围传播到外部?
【发布时间】:2021-02-17 04:26:30
【问题描述】:
// var outterResult = null;

using (var ctx = new TIS2APPContext())
{
    var results = (
        from t in (
            from route in ctx.ROUTEs
            join rstop in ctx.RSTOPs on route.ROUTEID equals rstop.ROUTEID
            join stop in ctx.STOPs on rstop.STOPID equals stop.STOPID
            select new { Route = route, RStop = rstop, Stop = stop }
        ).ToArray()
        group new { RStop = t.RStop, Stop = t.Stop } by t.Route into g
        select new { Route = g.Key, Stops = g.ToArray() }
    ).ToArray();
}

假设我在 using 范围内有一个复杂的 LINQ 结果。有没有办法让它逃到外面的世界?重点是匿名类型,在这种情况下我不会创建一个实际的类。

提前致谢。

【问题讨论】:

  • 只是映射到自定义类对象?或将数据库上下文注入更大的范围,因此您不受使用块的限制
  • 你最终得到了一个 toarray。您可以在使用外部使用数组类型的变量,然后分配结果。
  • 你能展示你想用它做什么吗? using 与问题没有任何关系,因为您可以将其吊起来。
  • 这完全取决于你想对数组做什么。
  • 这可能就是你要找的 - stackoverflow.com/questions/6624811/…

标签: c# linq types scope anonymous-types


【解决方案1】:

你不能为匿名对象声明类型,但是如果你在外部范围内使用具有相同字段的匿名对象,你可以给它一个提示。字段可以有虚拟值。

不过,您仍然受限于执行方法的范围。要在方法之外使用它,您需要将结果映射到元组,如果您不想使用类

var results = new[]
{
    new { Route = string.Empty, Stops = new List<string>() }
};

using (var db = new DbContext(""))
{
    results = (from o in db.Set<object>()
                    select new { Route = string.Empty, Stops = new List<string>() }
                    ).ToArray();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2023-03-28
    • 2012-11-15
    • 2012-10-14
    • 2020-10-17
    相关资源
    最近更新 更多