开发者

C# - Add List Count to JSON object

I have a Method that creates List<SomeObject>. The Collection is JSON serialized via JavaScriptSerializer. I am using LINQ's skip/take to return a subset of the total collection. So, I need to return the size of the total collection to the client as an object (this can't be calculated on the client side because it only has a subset).

I could hack it. Just, add int TotalSize as a 开发者_如何学Pythonmember of SomeObject.

I would rather not repeat this Member N times as I only need it once. I also don't want to perform some terrible OO by adding a member which doesn't really belong to the class.

Is there anything else I can do in order to add this new member to my JSON object?


Why not make a complex object?

public class SomeObjectSet
{
     public int TotalSetCount { get; set; }
     public List<SomeObject> Items { get; set; }

     public SomeObjectSet(List<SomeObject> subset, int totalCount)
     {
          items = subset;
          TotalSetCount = totalCount;
     }
}

Then, you simply make your new object and assign the data in the constructor, and your JSON should look like so:

{
     TotalSetCount: 100,
     Items: [
        { ... },
        { ... },
        { ... }
     ]
}

And in code you would just do this:

 var subset = mySuperset.Skip(...).Take(...);
 var totalSetCount = mySuperSet.Count();

 var serialization = _javascriptSerializer.Serialize(new SomeObjectSet(subset, totalSetCount));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜