C#, Linq

Implementing ToJSON() Extension Method

In my previous post Extension Methods in .net 3.5, I have given basic idea and example of Extension methods.

What is JSON (JavaScript Object Notation)

JSON is a lightweight data-interchange format. It is easy for humans
to read and write. It is easy for machines to parse and generate.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is
    realized as an object, record, struct, dictionary, hash table, keyed
    list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

e.g.

{"StudentID":2,"Name":"Amol","School":"MIT"}

For more details see json.org , JSON in JavaScript and wikipedia

Implementing ToJSON() Extension Method

JavaScriptSerializer class provides Serialize method which Converts an object to a JSON string.

using System.Web.Script.Serialization; 
public static class JSONHelper
{
public static string ToJSON(this object obj)
    {
        JavaScriptSerializer serializerObj = new JavaScriptSerializer();
        return serializerObj.Serialize(obj);
    }
}

Uses

There is no difference between calling an extension method and the methods that are actually defined in a object.

See below example,

List stringList=new List();
        stringList.Add("Amol");
        stringList.Add("Jon");
      string jsonString= stringList.ToJSON();
// ToJSON method will return,
// ["Amol","Jon"]
 
Student studObj = new Student();
        studObj.Name = "Amol";
        studObj.School = "MIT";
        studObj.StudentID = 2;
        string jsonString= studObj.ToJSON();
// ToJSON method will return,
//{"StudentID":2,"Name":"Amol","School":"MIT"}
Javascripts, Linq

Overview: jLinq

jLinq is a Javascript library that lets you write queries against arrays of javascript objects and JSON data.

Syntax and Examples

Syntax for jLinq is much similar to LINQ ,

var results = jLinq.from(data.users)
.startsWith("first", "a")
.orEndsWith("y")
.orderBy("admin", "age")
.select();

Some important commands

  • .startsWith( field?, value ): Check to see if the field starts with the specified value.
    //Some sample queries
    var results = jLinq.from(records)
    .startsWith("firstname", "jo") // first name starting with 'jo'
    .or("ji") // or first name starting with 'ji'
     
    var results = jLinq.from(records)
    //you can use an array of values to check
    .startsWith("firstname", ["a","e","i","o","u"])
    
  • .endsWith( field?, value ) : Check to see if the field starts with the specified value.
  • .contains( field?, value ) : Check to see if the field contains the specified value.
  • .match( field?, regexp ): Check to see if the
    value matches the regular expression. This command will still take case
    sensitivity into account.
  • .empty( field? ): Check to see if the field contains any value.
  • .greater( field?, value ): Check to see if the field is less than the provided value.

If the field is…

– a string, checks if it ends with the value
– an array, checks if the last element matches the value
– else, convert to a string and check returns jLinq Object

For all commands with examples see this.

Retrieve and Display Results

results[index][‘field’] will retrieve values from result object.

Following e.g. will retrieve data and displays in table,

var results = jLinq.from(data.users)
.startsWith("first", "a")
.toTable();
document.write(results);

Creating A Query Command

We can also create our own commands,

jLinq.extend({
    name:"evenValues", //the name of this command i.e. method
    type:"query", //the kind of command this is
    count:0, //how many parameters we expect
    method:function(query) {
        //determine how to evaluate the value being compared
        var compare = query.when({
            "string":function() {
                return query.value.length;
            },
            "array":function() {
                return query.value.length;
            },
            "other":function() {
                return query.helper.getNumericValue(query.value);
            }
        });
        //the actual comparison
        return compare % 2 == 0;
    }
});

E.g using custom command,

//this method is one way to do it
jLinq.from(data.users)
    .less("age", 30)
    .or()
    .evenValues()
    .select();

When you extend a query command , several additional operator prefixed name command are added to jLinq as well. Each of these perform the correct switches when they are used.

//this orEvenValues command is generated automatically
 
jLinq.from(data.users)
    .less("age", 30)
    .orEvenValues()
    .select();
C#, Linq

Lambda Expressions

What are Lambda Expressions?

C#  introduced the concept of anonymous methods, which allow code blocks to be written “in-line” where delegate values are expected.

Lambda Expressions provide a more concise, functional syntax for writing anonymous methods.They end up being super useful when writing LINQ query expressions – since they provide a very compact and type-safe way to write functions that can be passed as arguments for subsequent evaluation.

List stringList = GetList();
//filter list whose value starts with "am"
stringList = stringList.Where(name => name.StartsWith("am")).ToList();

e.g. In above example name is parameter name of string record.

C#, Linq

Extension methods

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

e.g which add extension method in string data type.

Defination of extension method

public static class test
{
    public static bool EqualWithIgnoreCase(this string str, string str2)
    {
        return (str.ToLower().Equals(str2.ToLower()));
    }
}

Uses:

string name = "Amol";
if (name.EqualWithIgnoreCase("amol"))
{
    //do something
}

(for more info visit: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx)