【问题标题】:how to retrieve count of different object types from JSON string in c#如何从 C# 中的 JSON 字符串中检索不同对象类型的计数
【发布时间】:2011-09-19 19:02:42
【问题描述】:

我有一个包含数据的数组 json 字符串:

[{"Name":"John","Age":"22"}, {"Name":"Jack","Age":"56"}, {"Name":"John","Age":"82"}, {"Name":"Jack","Age":"95"}]

我已经对数据进行了反序列化,并成功地将数据写入了 jquery 数据表。但是,我现在想在数据表中添加一列,以在一列中包含 john 名称和 jack 名称的计数。我可以通过循环说出以下内容来获得个人计数:

if (people[i].Name == "John")
   {
                name_count++;
   }
if (people[i].Name == "Jack")
   {
          name_count2++;
   }

如何让这些数据显示在与包含名称 jack 或 john 的行匹配的一列中?我正在使用 C#。提前致谢

【问题讨论】:

    标签: c# jquery datatables


    【解决方案1】:

    我建议使用 underscore.js (http://documentcloud.github.com/underscore)。您可以轻松实现您想要的任何类型的 map/reduce/select。举个例子:

    var people = [{"Name":"John","Age":"22"}, {"Name":"Jack","Age":"56"}, {"Name":"John","Age":"82"}, {"Name":"Jack","Age":"95"}];
    
    var num_johns = _(people).select(function(obj){ 
        return obj.Name === 'John'}).length;
    
    alert(num_johns); //alerts 2
    

    您甚至可以更进一步,使用一些柯里化 http://www.dustindiaz.com/javascript-curry/ 将 select 函数分解出来 - 取决于您的确切问题。

    【讨论】:

    • 感谢您的回复。但是我正在寻找一个 c# 解决方案。实际上,我有一份我的程序的副本,它使用客户端代码可以完全正常运行并获得正确的结果。然而,由于重新处理的数量,它现在变得非常缓慢,需要 C# 中的替代解决方案。
    【解决方案2】:

    你可以对数组做一些 linq 分组

        var peeps = from person in people 
            group person by person.name into bucket 
            select new { name = bucket.Key, count = bucket.Count() };
    

    这将创建一个具有 name 和 count 属性的可枚举匿名类型,您可以对其进行迭代以获取名称和名称的数量,例如:

    class Guy
        {
            public int age; public string name;
            public Guy( int age, string name ) {
                this.age = age;
                this.name = name;
            }
    
        }
    
        class Program
        {
            static void Main( string[] args ) {
                var GuyArray = new Guy[] { 
                new Guy(22,"John"),new Guy(25,"John"),new Guy(27,"John"),new Guy(29,"John"),new Guy(12,"Jack"),new Guy(32,"Jack"),new Guy(52,"Jack"),new Guy(100,"Abe")};
    
            var peeps = from f in GuyArray group f by f.name into g select new { name = g.Key, count = g.Count() };
    
                foreach ( var record in peeps ) {
                    Console.WriteLine( record.name + " : " + record.count );
                }
    
            }
        }
    

    将发出:

    John : 4
    Jack : 3
    Abe : 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-09
      相关资源
      最近更新 更多