C# 后台通过列表对JSON数据进行排序【高手请进】

powerchuangwai 2010-01-05 04:47:17

想基于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]

不知问题在哪里,请指教。。。。。。
...全文
460 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
powerchuangwai 2010-01-05
  • 打赏
  • 举报
回复
??
bzhyan 2010-01-05
  • 打赏
  • 举报
回复
up !!!
qqzeng-ip 2010-01-05
  • 打赏
  • 举报
回复
 /*参数定义:
datas 要排序的数组,其中每个元素是一个JSON对象{}
field 要排序的元素的字段名,将使用该字段进行排序
type 排序类型,如果为"down"则为降序排序,否则升序
*/
function SortData(datas, field, type) {
SortFun.field = field;
datas.sort(SortFun);
if (type == "down") {
datas.reverse();
}
}
function SortFun(data1, data2) {
if (data1[SortFun.field] > data2[SortFun.field]) {
return 1;
}
else if (data1[SortFun.field] < data2[SortFun.field]) {
return -1;
}
return 0;
}

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧