Linq Query Recursive

This question is taken from Stack Overflow : )..I had taught to myself  writing recursive query with LINQ.

Question Link 

Input : 


public class InputClass
{
public int id { get; set; }
public string text { get; set; }
public string icon { get; set; }
public int? parentId { get; set; }

}

static void Main(string[] args)
{
var inputList = new List<InputClass>();
inputList.Add(new InputClass() { id = 1, text = "Item #1" });
inputList.Add(new InputClass() { id = 2, text = "Item #2" });
inputList.Add(new InputClass() { id = 3, text = "Item #3" });
inputList.Add(new InputClass() { id = 4, text = "SubItem #1", parentId = 1 });
inputList.Add(new InputClass() { id = 5, text = "SubItem #2", parentId = 1 });
inputList.Add(new InputClass() { id = 6, text = "SubItem #3", parentId = 2 });
inputList.Add(new InputClass() { id = 7, text = "Sub-Sub Item #1", parentId = 4 });

}

Output:

write a linq query to generate all child elements when parent id is passed.

Example :  when ParentId is 1 ,then the following output must be produced

ID  Name
4   Subitem #1
5   Subitem #2
7   Sub-Sub Item #1

Note : Id 4 & 5 has parent id of 1 and ID 7 has parent id of 4 which inturn points to parent id 1.

Code :

1.First we will write a method to return list of elements that matches the parent id.

Method :
 private static List<InputClass> GetAllChildElements(int parentid, List<InputClas>input)
 {
 return input.Where(x => x.parentId == parentid).ToList();
 } 
This method would return 4& 5 when parent id is passed as 1. 2.Next we must check if the returned list has any child elements associated with it. In this case returned list Id 4 has a reference to child element 7. we must again execute the same 
query but now the parent id would be returned list Ids.


 private static List<InputClass> GetRecursiveList(int p, List<InputClass> inputList)
 {
 var result = inputList.Where(x => x.parentId == p).ToList();
 var temp = new List<InputClass>();
 foreach (var inputClass in result)
 {
 temp.AddRange(GetRecursiveList(inputClass.id, inputList));
 }
 var t=result.Union(temp);
 return t.ToList();
 }

#Things you may want to know about Constants and Readonly

constants (const): The value of const is set at compile time(the value must be set when you declare it) and cannot  be changed at run time.

ReadOnly : They need not be initialized  when declared ,but must be initialized in constructor. They could be initialized else where other than constructor.

  1. const are themselves static, so you cannot declare
     public static const int s =1 --Error cannot be static

2 .const can be used only with primitive types(exception is Strings) .i.e it does not make sense to use custom class with const.

 public cosnt myclass = new myclass() ---Error must be a compile time value 

.

Its possible for you to do that with ReadOnly.

 

#11 Bind Attribute in MVC

There are cases where you want to limit/restrict  the properties of a model that is submitted to the server.

Model class :


[Bind(Exclude="Rid")] ---- Rid properties is excluded from model.

public class ReviewModel

{
public int Rid { get; set; } -- AutoGenerated ,User need not submit it
public String RName { get; set; }
public String RLocation { get; set; }
public int Rating { get; set; }
}

In the above example,Rid is Auto generated and user need not submit it when posted from View. Rid is excluded by using Bind attribute annotation. 

 

 

#10 RenderSection Method in Layout

In layout Pages,renders the content of named Section.

RenderSection("footer",false) ---If set to false,then view need not have a section

The above code expects the Section “footer” to be used and its mandatory,so typically view must have a section named footer.

{
    Layout = ~/Views/Shared/_Layout.cshtml;
}
section footer
{
This is sample footer
}

Working principle of RenderSection :

rendersection

#7 Implementing Custom Error Attributes

We can implement Custom Error Handling attribute by implementing ActionFilterAttribute.It has Four methods OnActionExecuted,OnActionExecuting,OnResultExecuted,OnResultExecuting methods which would be overridden in custom class.


class LogAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
}

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}

public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
}

public override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
}
}

#6 Handling Error in MVC-HandleErrorAttribute

By Default if an exception occurs in action method,it bubbles up to the FilterConfig which holds the  HandleError that is responsible for catching the exception.Framework also provides a View named “Error.cshtml” in shared folder that is responsible to show the exceptions in UI.


public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}