Skip to main content

Posts

Showing posts with the label c# 4.0

Reverse a given linked list in c#

In this post I will show you how to reverse a  given linked list in c#.For example a given linked list as show below10->20->30-NULLthen output should be30->20->10-NULLusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algo { public class List { public List Next { get; set; } public int Value { get; set; } public List(int value) { Value = value; } public override string ToString() { List current = this; StringBuilder builder = new StringBuilder(); while (current!=null) { builder.Append(current.Value + "->"); current = current.Next; } return builder.ToString(); } public List ReverseList() { List prev = null; List next = null; List current = this; …

How to print out all path from root to leaf of a given binary tree

This is continuation of my post How to create binary tree in c#.In this post I will show you how to print all path from root to leaf of a given binary tree in c#.Let’s consider following binary tree.             *       4
             *    2     5
             *  1    3     For above tree there are three path from root to leafPath 1 : 4 2 1Path 2: 4 2 3Path 3: 4 5 public void PrintPath() { int[] path = new int[100]; printPaths(_root, path, 0); } private void printPaths(Node node, int[] path, int pathLen) { if (node == null) return; // append this node to the path array path[pathLen] = node.Data; pathLen++; // it's a leaf, so print the path that led to here if (node.Left == null && node.Right == null) { PrintArray(path, pathLen); } else { // otherwise try both subtre…

How to find min or max value in a given binary tree

This is continuation of my post How to create binary tree in c#.In this post I will show you how to find max or min value in a given binary tree.Min Value: Loop down to find the leftmost leaf Max Value: Loop down to find the rightmost leaf public int FindMinValue() { return FindMinValue(_root); } private int FindMinValue(Node root) { if (root == null) return -1; else { Node current = root; while (current.Left!=null) { current = current.Left; } return current.Data; } } public int FindMaxValue() { return FindMaxValue(_root); } private int FindMaxValue(Node root) { if (_root == null) return -1; else { Node current = root; while (curre…

How to calculate max depth of given binary tree in c#

This is continuation of my post How to create binary tree in c#.In this post I will show you how to calculate max depth of a given binary tree in c#.MaxDepth of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node. public int MaxDepth() { return MaxDepth(_root); } private int MaxDepth(Node root) { if (root == null) return -1; // compute the depth of each subtree else { int leftDepth = MaxDepth(root.Left); int rightDepth = MaxDepth(root.Right); //Return max of left or right tree. return 1 + Math.Max(leftDepth, rightDepth); } }

How to calculate size of binary tree

This is continuation of my post How to create binary tree in c# .In this post I will show you how to find size of binary tree.Size of binary tree is number of nodes in a given tree.Following is the recursive implementation of size function //Compute the number of nodes in a tree. public int Size() { return Size(_root); } private int Size(Node root) { if (root == null) return 0; return 1 + Size(root.Left) + Size(root.Right); }

How to create binary tree in c#

A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree. Implementationusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BTree { public class Node { public int Data { get; set; } public Node Left { get; set; } public Node Right { get; set; } public Node() { } public Node(int data) { this.Data = data;…

How to create instance of generic class using reflection

In this post I am going to show how to create instance of generic class using c# reflection.The trick is to use the MakeGenericType to make the argument(s) and then call create Instance. Here is a code snippet:Type d1 = typeof(List<>); Type[] typeArgs = { typeof(string) }; Type makeme = d1.MakeGenericType(typeArgs); object o = Activator.CreateInstance(makeme); List<string> itsMe = o as List<string>;

How to create Fibonacci series using Linq

In this post I am going to show you how to generate fiboancci number series using Linq.What is Fibonacci series : The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it. public static IEnumerable<int> Fib(int n) { List<int> fibs = new List<int>(); Enumerable.Range(0, n) .ToList() .ForEach(f => fibs.Add((f <= 1 ? 1 : fibs[f - 2] + fibs[f - 1]))); return fibs; }

How DataContract serialize CLR object into XML

In this post,I am going to show you how DataContract export DataContract into xsd ,and then how an object is converted into xml.





using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.Xml.Schema; using System.Xml; namespace DataContract_Demo {     [DataContract(Namespace = "http://aspdotnetcodebook.blogspot.com", Name = "Person")]     publicclass Person     {         [DataMember(Name = "FirstName")]         publicstring FirstName { get; set; }         [DataMember(Name = "LastName")]         publicstring LastName { get; set; }     }     class Program     {         staticvoid Main(string[] args)         {             GenerateXsd();             GenerateXML();         }         privatestaticvoid GenerateXsd()         {             XsdDataContractExporter exporter = new XsdDataContractExporter();             exporter.Export(typeof(Person));             foreach (XmlS…

How To create your own DynamicObject

In this post i will show how to create your own dyanamic object in c# 4.0.Create a class and Inherit it from DyanicObject (Provides a base class for specifying dynamic behavior at run time. This class must be inherited from; you cannot instantiate it directly).It has following virtual method that you must override to add dynamic behavior to your class. // Summary:// Returns the enumeration of all dynamic member names.//// Returns:// The list of dynamic member names.publicvirtual IEnumerable<string> GetDynamicMemberNames(); //// Summary:// The provided MetaObject will dispatch to the Dynamic virtual methods. The// object can be encapsulated inside of another MetaObject to provide custom// behavior for individual actions.//// Parameters:// parameter:// The expression representing the MetaObject to dispatch to the Dynamic virtual// methods.//// Returns:// The object of the System.Dynamic.DynamicMetaObject type.publicvirtual DynamicMetaObje…

ExpandoObject and Dynamic Programming in c# 4.0

ExpandoObject is a new Object in the .NET Framework that allows you to add and remove properties, methods, and events at runtime just like JavaScript Object. The following example demonstrates how to add two new values and a method in c# and Javascript. C# Code JavaScript Code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Dynamic; namespace CSharpDemo { class Program { staticvoid Main(string[] args) { dynamic customer = new ExpandoObject(); customer.City = "Gurgaon"; customer.Country = "India"; customer.FullAddress = new Action(() => Console.WriteLine( customer.City + " " + customer.Country )); customer.FullAddress(); Console.ReadKey(); } } } function GetCusomer() { var customer = new Object(); …

Named and Optional Parameters

Named parameters allow you to pass parameters into a function in any order. To use a named parameter, simply specify the parameter name followed by a colon and then the value you are passing into a function. The following code illustrates passing the named parameter. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpDemo { class Program { staticvoid Main(string[] args) { //Calling mehtod without named parameter AddNumbers(1, 2, 3); //Calling method with named parameter AddNumbers(c: 3, b: 2, a: 4,d:10); Console.ReadLine(); } publicstaticvoid AddNumbers(int a, int b, int c, int d = 0) { int sum = a + b + c + d; Console.WriteLine("Sum={0}", sum); } } } There some rules you need to be aware of when working with named parameters. Non-optional parameters must be declared …