Skip to content

Instantly share code, notes, and snippets.

@antdimot
Last active August 21, 2019 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antdimot/6401a681e1ac8dace8de4db38acde434 to your computer and use it in GitHub Desktop.
Save antdimot/6401a681e1ac8dace8de4db38acde434 to your computer and use it in GitHub Desktop.
Example of sum for json array
using System;
using System.IO;
using Newtonsoft.Json;
namespace ConsoleApp1
{
/// <summary>
/// Example of sum for json array
/// </summary>
class Program
{
static void Main( string[] args )
{
var json = "[1,'2',3,'a',4]";
JsonTextReader reader = new JsonTextReader( new StringReader( json ) );
int result = 0;
while( reader.Read() )
{
if( reader.Value != null )
{
switch( reader.TokenType )
{
case JsonToken.Integer:
result += Convert.ToInt32( reader.Value );
break;
case JsonToken.String:
if( Int32.TryParse( reader.Value.ToString(), out int r ) )
{
result += r;
}
break;
default:
break;
}
}
}
Console.WriteLine( "The sum of array is :" + result );
Console.WriteLine( "End of program." );
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment