C# 后台通过列表对JSON数据进行排序【高手请进】
想基于C# 在后台通过列表基于字段属性对JSON数据进行排序
首先感谢 xuyiazl 提供的方法。
想在后台对JSON数据进行排序,有一个按钮 和 一个textBox,思路是通过列表对JSON数据进行排序,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
[DataContract]
public sealed class FooDef
{
[DataMember(Name = "ID", IsRequired = true)]
public string ID { get; set; }
[DataMember(Name = "Order", IsRequired = true)]
public string Order { get; set; }
}
static List<T> Deserialize<T>(string str)
{
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(List<T>));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(str)))
{
List<T> entities = (List<T>)json.ReadObject(stream);
stream.Close();
return entities;
}
}
private void button1_click(object sender,EventArgs e)
{
string bar = "[{\"ID\":\"3\",\"Order\":\"9\"},{\"ID\":\"1\",\"Order\":\"6\"},{\"ID\":\"2\",\"Order\":\"8\"}]";
List<FooDef> newEntities = Deserialize<FooDef>(bar);
var s = from l in newEntities orderby l.ID select l;
textBox1.Text = s.ToString();
}
感觉逻辑上没有问题,但是结果如下:
textBox1显示内容:
System.Linq.OrderedEnumerable.2[order20100105.Form1+FooDef,system.string]
不知问题在哪里,请指教。。。。。。