想基于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]   不知问题在哪里,请指教

解决方案 »

  1.   

     /*参数定义:
            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;
        }