将项目附加到对象

0 c# linq json json.net

我创建了一个Linq语句来获取数据库中的项目列表.所以我需要循环查询并追加到对象然后序列化然后才能在javascript中用作json.问题是我无法附加到声明的对象'obj'.谁能帮忙?

DataContext dataContext = new DataContext();
        var query = from qr in dataContext.tblStocks
                    where qr.enable == true
                    select qr;

        var obj = new JObject();

        foreach (var item in query)
        {
            //obj = new JObject();
            obj = ( new JObject(
                    new JProperty("stockID",item.stockID),
                    new JProperty("itemDepartmentID", item.itemDepartmentID),
                    new JProperty("item" , item.item),
                    new JProperty("description", item.description),
                    new JProperty("stockAmount", item.stockAmount),
                    new JProperty("priceExlVat", item.priceExlVat),
                    new JProperty("vat", item.vat),
                    new JProperty("priceIncVAT", item.priceIncVAT),
                    new JProperty("upc1", item.upc1),
                    new JProperty("upc2", item.upc2)
                ));


       }
        var serialized = JsonConvert.SerializeObject(obj);
        return serialized;
Run Code Online (Sandbox Code Playgroud)

Ric*_*ard 5

obj每次循环都会重新分配,因此所有其他数据都将丢失.

更容易创建数组:

obj = new JArray();

foreach (var item in query) {
  obj.Add(new JObject(
            new JProperty(...),
            ...));
}
Run Code Online (Sandbox Code Playgroud)