【问题标题】:C# Linq Subquery in foreachforeach 中的 C# Linq 子查询
【发布时间】:2015-10-18 18:00:15
【问题描述】:

我有这个 Linq 查询(Foo 有一个 DateTime 变量):

var tableFoo = context.GetTable<Foo>();
var tableBar = context.GetTable<Bar>();

var preselect = tableFoo.Where(o => o.Name == "");

List<Foo> foos = new List<Foo>();

foreach (Foo f in preselect) //System.InvalidCastException comes here at the second iteration (Unable to cast to DateTime)
{
    Foo foo = f;

    var subselect = tableBar.Where(o => o.Id == foo.Id);
    foreach (Bar bar in subselect)
    {
        foo.bars.Add(bar);
    }
    foos.Add(foo);
}

preselect 包含 1 个对象时,它可以正常工作。
但是如果preselect 包含超过 1 个对象,它将无法按预期工作。在第一次迭代中它有效,但在第二次我得到一个System.InvalidCastException
它与内部 subselect 有关,因为如果我移除内部 foreach,它会完美运行。
我认为这与this 有关。但我不知道要改变什么。

preselect 中的子选择不适合我的应用程序架构

【问题讨论】:

    标签: c# linq sqlite


    【解决方案1】:

    我是这样解决的(我知道这不是很优雅):

    var tableFoo = context.GetTable<Foo>();
    var tableBar = context.GetTable<Bar>();
    
    var preselect = tableFoo.Where(o => o.Name == "");
    
    List<Foo> foos = new List<Foo>();
    
    foreach (Foo f in preselect) //System.InvalidCastException comes here at the second iteration (Unable to cast to DateTime)
    {
        Foo foo = f;
    
        foos.Add(foo);
    }
    
    foreach (Foo foo in foos)
    {
        var subselect = tableBar.Where(o => o.Id == foo.Id);
        foreach (Bar bar in subselect)
        {
            foo.bars.Add(bar);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2013-06-23
      • 2010-11-16
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多