使用LINQ从Ienumerable创建JSON对象



我正在尝试使用LINQ JSON创建使用http://james.newtonking.com/json (JSON.NET)框架的JSON对象。

基本上我试图从IEnumerable输出创建一个特定的结构。有类似产品->实际,预测,目标。

LINQ to XML语句工作良好,我可以看到结果。它是由于延迟执行和延迟评估在LINQ到XML?是,如何解决

这是我的LINQ to XML方法的样子

IEnumerable resultSet = (xmlDoc.Root.Descendants(ns + "Row").Select(result => new
        {
            MonthYearShortName = (DateTime)result.Element(ns + "Column0"),
            Product = (String)result.Element(ns + "Column1"),
            Actual = (decimal)result.Element(ns + "Column2"),
            Forecast = (decimal)result.Element(ns+"Column3"),
            Target = (decimal)result.Element(ns + "Column4"),
        }));

这是我的LINQ到JSON。我使用的示例来自http://james.newtonking.com/json/help/index.html?topic=html/CreatingLINQtoJSON.htm

JObject rss =
                resultSet.Select(p => new JObject(p.Product,
                    new JProperty("MonthYearShortName", p.MonthYearShortName),
                    new JProperty("Actual", p.Actual),
                    new JProperty("Forecast", p.Forecast),
                    new JProperty("Target", p.Target)));
            Console.WriteLine(rss.ToString());

当我执行LINQ to JSON语句时,我得到以下错误消息

Error   5   'System.Collections.IEnumerable' does not contain a definition for 'Select' and no extension method 'Select' accepting a first argument of type 'System.Collections.IEnumerable' could be found 
我usings

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Extensions = System.Xml.Linq.Extensions;

不确定为什么我无法在第二个LINQ到JSON语句中进行选择。

请帮忙就太好了。

谢谢!

Select扩展方法定义在泛型IEnumerable<T>接口上(而不是非泛型IEnumerable)。

要编译代码,首先需要调用Cast<>()

JObject rss =
         resultSet.Cast<XElement>().Select(p => new JObject(p.Product,
                    new JProperty("MonthYearShortName", p.MonthYearShortName),
                    new JProperty("Actual", p.Actual),
                    new JProperty("Forecast", p.Forecast),
                    new JProperty("Target", p.Target)));
            Console.WriteLine(rss.ToString());

(或以其他方式转换为通用IEnumerable<resultSet>)

如果您试图获取JSON字符串,则此代码应该有效:

 var resultSet = (xmlDoc.Root.Descendants("Row").Select(result => new
        {
            MonthYearShortName = (DateTime)result.Element(ns + "Column0"),
            Product = (String)result.Element("Column1"),
            Actual = (decimal)result.Element("Column2"),
            Forecast = (decimal)result.Element("Column3"),
            Target = (decimal)result.Element("Column4"),
        }));
 var json = JsonConvert.SerializeObject(resultSet);
 Console.WriteLine(json);

最新更新