Tuesday, September 17, 2019

Generate tree view with json data by parentId using jquery

HTML:
           <div id="container"></div>

CSS:
           ul {
                 margin-left: 20px;
                list-style-type: disc;
            }

JS:
     function buildNestedList(treeNodes, rootId) {
                     var nodesByParent = {};

                     $.each(treeNodes, function(i, node) {
                         if (!(node.parent in nodesByParent)) nodesByParent[node.parent] = [];
                               nodesByParent[node.parent].push(node);
                      });

  function buildTree(children) {
    var $container = $("<ul>");
   
    if (!children) return;
    $.each(children, function(i, child) {
      $("<li>", {text: child.name})
      .appendTo($container)
      .append( buildTree(nodesByParent[child.id]) );
    });
    return $container;
  }
  return buildTree(nodesByParent[rootId]);
}
   
var treeNodes = [
    {parent:-1,id:0,name:'root'},
    {parent:0,id:1,name:'x'},
    {parent:0,id:2,name:'y'},
    {parent:1,id:3,name:'z'},
    {parent:1,id:4,name:'w'},
    {parent:1,id:5,name:'c'},
    {parent:2,id:6,name:'d'}
];

$("#container").append( buildNestedList(treeNodes, 0) );


Result:
     
  • x
    • z
    • w
    • c
  • y
    • d

Monday, September 9, 2019

IEnumerable -> ICollection -> IList -> IQueryable for C#

IEnumerable
Can not adding, deleting, updating, etc. read only mode. Just use a container to contain a list of items. It is the most basic type of list container.
An IEnumerable  supports filtering elements using where clause.
More faster then list.

IEnumerable is suitable just for iterating through collection and you cannot modify (Add or Remove) data. IEnumerable brings ALL data from server to client, then filters them, assume that you have a lot of records so IEnumerable puts overhead on your memory.

ICollection
ICollection is another type of collection, which derives from IEnumerable and extends it’s functionality to add, remove, update element in the list. 
ICollection supports enumerating over the elements, filtering elements, adding new elements, deleting existing elements, updating existing elements and getting the count of available items in the list.
IList
IList extends ICollection. An IList can perform all operations combined from IEnumerable and ICollection, and some more operations like inserting or removing an element in the middle of a list.
You can use a foreach loop or a for loop to iterate over the elements.
IQueryable
IQueryable extends ICollection. An IQueryable generates a LINQ to SQL expression that is executed over the database layer.