【问题标题】:Explicit conversion of IEnumerable<AnonymousType#1>IEnumerable<AnonymousType#1> 的显式转换
【发布时间】:2013-08-29 15:23:01
【问题描述】:

我有一个使用 LINQ 对两个 DataTable 执行不匹配查询的方法。它产生了一个错误,通过在线查看我已经确定了我认为错误发生的位置,但我不知道如何解决它。

public IEnumerable<int> UnbilledAuditKeys(DataTable audits, string keyFieldName) {
    var billedAudits =
        from x in this.GetBilledAudits().AsEnumerable()
        select new {
            k = x.Field<int>(keyFieldName)
        };

    var allAudits =
        from x in audits.AsEnumerable()
        select new {
            k = x.Field<int>(keyFieldName)
        };

    var unbilled =
        from a in allAudits
        join b in billedAudits on a.k equals b.k
            into combined
        from c in combined.DefaultIfEmpty()
        where c == null
        select new { // This is what's causing the error (I think)
            k = a.k
        };

    return unbilled; // This line the compiler is rejecting
}

返回的错误是

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.IEnumerable<int>'. An explicit conversion exists (are you missing a cast?)

我不知道如何解决它。我已经尝试过将整个 LINQ 表达式转换为 IEnumerable 等显而易见的方法,但这会产生运行时异常。

任何想法将不胜感激!

编辑:

最后的方法:

public IEnumerable<int> UnbilledAuditKeys(DataTable rosliAudits, string keyFieldName) {
    var billed = this.GetBilledAudits().AsEnumerable().Select(x => x.Field<int>(keyFieldName));
    var allaudits = rosliAudits.AsEnumerable().Select(x => x.Field<int>(keyFieldName));
    var unbilled = allaudits.Except(billed);
    return unbilled;
}

【问题讨论】:

    标签: c# linq join


    【解决方案1】:

    简单修复:

    var unbilled =
        from a in allAudits
        join b in billedAudits on a.k equals b.k
            into combined
        from c in combined.DefaultIfEmpty()
        where c == null
        select a.k;
    

    另外,另外两个查询似乎不需要匿名结构,最后一个可以大大简化:

    public IEnumerable<int> UnbilledAuditKeys(DataTable audits, string keyFieldName) {
        var billedAudits =
            from x in this.GetBilledAudits().AsEnumerable()
            select x.Field<int>(keyFieldName);
    
        var allAudits =
            from x in audits.AsEnumerable()
            select x.Field<int>(keyFieldName);
    
        var unbilled = allAudits.Except(billedAudits); // LINQ has many useful methods like this
    
        return unbilled;
    }
    

    【讨论】:

    • 我爱 LINQ !!!但我对它太陌生了,我仍然像对待 SQL 一样对待它。太感谢了!这工作得很好:)
    【解决方案2】:

    直接选择您的字段,而不是创建新的匿名类型:

    var unbilled =
        from a in allAudits
        join b in billedAudits on a.k equals b.k
            into combined
        from c in combined.DefaultIfEmpty()
        where c == null
        select a.k;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 2015-06-12
      相关资源
      最近更新 更多