如何正确地结合不同的IQueryables,然后在JSON中序列化它们

时间:2016-09-26 17:24:17

标签: c# linq

我有两种不同的数据源。例如,假设一个源包含id和lastnames,第二个源包含其他id和lastnames。我想将它们组合成JSON,如下所示:

dp2[n-1]

为了实现它,我正在尝试来自不同来源的“联盟”ID “Union”来自不同来源的姓氏,之后,在一个名为“full”的匿名类型变量中“Zip”它。

{
  "Full": [
    {
      "id": 1,
      "lastname": "Doe"
    },
    {
      "id": 5,
      "lastname": "Smith"
    }
  ]
}

idsFromOneSource idsFromOtherSource var ids = idsFromOneSource.Union(idsFromOtherSource); var lastNames = lastNamesFromOneSource.Union(lastNamesFromOtherSource); var full = new { Full = ids.Zip(lastNames, (i, l) => new { id = i, lastName = l }) }; return JsonConvert.Serialise(full); lastNamesFromOneSource lastNamesFromOtherSource 为{{1} }

我收到了这个错误。

  

LINQ to Entities无法识别方法'System.Linq.IQueryable IQueryable<int> 2 [System.Int32,System.String]] Zip [Int32,String,&lt;&gt; f__AnonymousType2 IQueryable<string> 1 [System.Int32],System.Collections.Generic.IEnumerable 1[<>f__AnonymousType2 1 [System.Func 2](System.Linq.IQueryable 2 [System.Int32,System.String]]])'方法,此方法无法翻译进入商店表达。

对于序列化我正在使用NewtonSoft Json.net,但看起来不是问题。我将不胜感激任何帮助。

2 个答案:

答案 0 :(得分:3)

你不能在linq-to-Entities中Zip。您可以通过调用AsEnumerable 将它们转换为linq-to-objects调用:

    var ids = idsFromOneSource.Union(idsFromOtherSource);
    var lastNames = lastNamesFromOneSource.Union(lastNamesFromOtherSource);

    var full = new
    {
        Full = ids.AsEnumerable().Zip(lastNames, (i, l) => new { id = i, lastName = l })
    };
    return JsonConvert.Serialise(full);

但您可能知道的一个警告是,集合需要完全对齐(以相同的顺序)。看起来有一些关键来加入不同的集合会更安全。

答案 1 :(得分:2)

LINQ to Entities不支持

#!/bin/awk BEGIN { start = 2 end = 6 } { if( ($2 >= start) && ($2 <= end) ) { sum = sum + $2 n = n + 1 } } END { print ( n!= 0) ? sum / n : 0 } #eof# 。虽然可以尝试在调用Zip之前实现这些值(如D Stanley所示),但依赖它可能不是一个好主意(如Zip那样)关于两个查询之间匹配的值,特别是因为如果一个姓氏来源与其他姓氏来源具有一些​​相同的值,Zip会以不同的方式匹配。

我建议您重新考虑源查询,看看您是否可以选择ID和每个来源的姓氏。无论你在哪里存储姓氏,这些姓氏和身份证之间都应该有一些关系,对吧?因为关系数据库应该如何工作,对吧? Union只要具有完全相同的形状,就可以处理复杂的类型,所以这样的事情应该有效:

Union

但是如果您的来源不是来自相同的Entity Framework上下文,那么您需要实现这两个来源,以便var idsAndFullNames = idsAndFullNamesFromOneSource .Select(src => new { id = src.ID, fullName = src.FullName }) .Union( idsAndFullNamesFromOtherSource.Select(src => new { id = src.Id, fullName = src.full_name }) .ToList(); 在内存中发生:

Union()
相关问题