This project is read-only.

Constructing $linq objects

There are a couple of ways to create a linq object from an array:
var arr = [1, 2, 3, 4, 5];

var col1 = linq.from(arr);  // using 'from' method
var col2 = $linq(arr);      // using $linq shortcut
var col3 = new linq(arr);   // using constructor
Using the constructor to create a $linq object is sometimes useful because the constructor has a second parameter that indicates whether or not to make an internal copy of the array (with the default of making a copy). Using the linq.from() and $linq() methods to create a linq object always makes an internal copy of the array.
var arr = [1, 2, 3, 4, 5];

var col = new linq(arr, false);  // don't make an internal copy of the array

// result1.length is '2'
var result1 = col.where("x => x > 3").toArray();

arr.push(6);
arr.push(7);

// result2.length is '4'
var result2 = col.where("x => x > 3").toArray();
In addition to an array, the $linq() and linq.from() methods will accept:
Parameter Value linq Object Result
"null" an empty linq object
a jQuery object a linq object containing the same elements that the jQuery object enumerates
another linq object a copy of the given linq object
any other object a linq object containing parameter value as a single object

// arr1 = []
var arr1 = $linq(null).toArray();  // also, $linq().toArray()

// using jQuery--arr2 contains all of the "links" on the page
var temp1 = $('a');
var arr2 = $linq(temp1).toArray();

// arr3 = [1, 2, 3]
var temp2 = linq.from([1, 2, 3]);
var arr3 = $linq(temp2).toArray();

// arr4 = [{text: "testing"}]
var temp3 = {text: "testing"};
var arr4 = $linq(temp3).toArray();

linq.range()

The linq.range() method creates a linq object that contains a range of integer values.
// arr == [1, 2, 3, 4, 5]
var arr = linq.range(1, 5).toArray();
The linq.range() method has an optional third parameter that indicates the amount by which to increment each value in the range.
// arr == [1, 4, 7, 10]
var arr = linq.range(1, 10, 3).toArray();

linq.repeat()

The linq.repeat() method creates a linq object that contains an object repeated a given number of times.
// arr == ["test", "test", "test", "test"]
var arr = linq.repeat("test", 4).toArray();

linq.matches()

The linq.matches method creates a linq object that contains the results of a regular expression match. This method can be passed the regular expression pattern as either a string or a RegExp object. While specific RegExp flags can be passed to the linq.matches method, the "g" flag is implied.
var text = "This is a test";
var pattern1 = "\\w+";
var pattern2 = /\w+/;

// arr1 and arr2 will both equal ['This', 'is', 'a', 'test']
var arr1 = linq.matches(text, pattern1);
var arr2 = linq.matches(text, pattern2);

Last edited Sep 19, 2012 at 6:46 AM by battousai999, version 4