Showing posts with label c# 4.0. Show all posts
Showing posts with label c# 4.0. Show all posts

Sunday, March 29, 2015

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 below

10->20->30-NULL

then output should be

30->20->10-NULL

 

image

using 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;
            while (current!=null)
            {
                next = current.Next;
                current.Next = prev;
                prev = current;
                current = next;
            }
            return prev;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List list = new List(10);
            list.Next = new List(20);
            list.Next.Next = new List(30);
            Console.WriteLine(list);
            var rev = list.ReverseList();
            Console.WriteLine(rev);
        }
    }
}

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 leaf

Path 1 : 4 2 1

Path 2: 4 2 3

Path 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 subtrees 
                printPaths(node.Left, path, pathLen);
                printPaths(node.Right, path, pathLen);
            }
        }

        private void PrintArray(int[] path, int pathLen)
        {
            for (int i = 0; i < pathLen; i++)
            {
                Console.Write(path[i] + " ");
            }
            Console.WriteLine();
        }

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 (current.Right!=null)
                {
                    current = current.Right;
                }
                return current.Data;
            }
        }

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.

download

Implementation

using 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;

        }
    }
    public class BinaryTree
    {
        private Node _root;
        public BinaryTree()
        {
            _root = null;
        }
        public void Insert(int data)
        {
            // 1. If the tree is empty, return a new, single node 
            if (_root == null)
            {
                _root = new Node(data);
                return;
            }
            // 2. Otherwise, recur down the tree 
            InsertRec(_root, new Node(data));
        }
        private void InsertRec(Node root, Node newNode)
        {
            if (root == null)
                root = newNode;

            if (newNode.Data < root.Data)
            {
                if (root.Left == null)
                    root.Left = newNode;
                else
                    InsertRec(root.Left, newNode);

            }
            else
            {
                if (root.Right == null)
                    root.Right = newNode;
                else
                    InsertRec(root.Right, newNode);
            }
        }
        private void DisplayTree(Node root)
        {
            if (root == null) return;

            DisplayTree(root.Left);
            System.Console.Write(root.Data + " ");
            DisplayTree(root.Right);
        }
        public void DisplayTree()
        {
            DisplayTree(_root);
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            BinaryTree tree = new BinaryTree();
            Node root = new Node();

            tree.Insert(4);
            tree.Insert(2);
            tree.Insert(5);
            tree.Insert(1);
            tree.Insert(3);
            tree.DisplayTree();
        }
    }
}

Saturday, February 28, 2015

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>;

Tuesday, February 17, 2015

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;


        }

Tuesday, December 7, 2010

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")]
    public class Person
    {
        [DataMember(Name = "FirstName")]
        public string FirstName { get; set; }
        [DataMember(Name = "LastName")]
        public string LastName { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            GenerateXsd();
            GenerateXML();


        }

        private static void GenerateXsd()
        {

            XsdDataContractExporter exporter = new XsdDataContractExporter();
            exporter.Export(typeof(Person));
            foreach (XmlSchema xml in exporter.Schemas.Schemas("http://aspdotnetcodebook.blogspot.com"))
            {
                var writer = new XmlTextWriter(Console.Out) { Formatting = Formatting.Indented };
                xml.Write(writer);

            }
        }

        private static void GenerateXML()
        {

            var Objwriter = new XmlTextWriter(Console.Out) { Formatting = Formatting.Indented };
            var ser = new DataContractSerializer(typeof(Person));
            ser.WriteObject(Objwriter, new Person() { FirstName = "X", LastName = "Y" });
        }
    }
}

Saturday, February 27, 2010

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.
        public virtual 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.
        public virtual DynamicMetaObject GetMetaObject(Expression parameter);
        //
        // Summary:
        //     Provides the implementation of performing a binary operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   arg:
        //     The right operand for the operation.
        //
        //   result:
        //     The result of the operation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result);
        //
        // Summary:
        //     Provides the implementation of converting the DynamicObject to another type.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   result:
        //     The result of the conversion.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryConvert(ConvertBinder binder, out object result);
        //
        // Summary:
        //     Provides the implementation of creating an instance of the DynamicObject.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   args:
        //     The arguments used for creation.
        //
        //   result:
        //     The created instance.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryCreateInstance(CreateInstanceBinder binder, object[] args, out object result);
        //
        // Summary:
        //     Provides the implementation of performing a delete index operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   indexes:
        //     The indexes to be deleted.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes);
        //
        // Summary:
        //     Provides the implementation of deleting a member.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryDeleteMember(DeleteMemberBinder binder);
        //
        // Summary:
        //     Provides the implementation of performing a get index operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   indexes:
        //     The indexes that will be used in the operation.
        //
        //   result:
        //     The result of the operation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result);
        //
        // Summary:
        //     Provides the implementation of getting a member.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   result:
        //     The result of the get operation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryGetMember(GetMemberBinder binder, out object result);
        //
        // Summary:
        //     Provides the implementation of invoking the DynamicObject.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   args:
        //     The arguments that will be used for the invocation.
        //
        //   result:
        //     The result of the invocation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryInvoke(InvokeBinder binder, object[] args, out object result);
        //
        // Summary:
        //     Provides the implementation of calling a member.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   args:
        //     The arguments that will be used for the invocation.
        //
        //   result:
        //     The result of the invocation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result);
        //
        // Summary:
        //     Provides the implementation of performing a set index operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   indexes:
        //     The indexes that will be used in the operation.
        //
        //   value:
        //     The value to set.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value);
        //
        // Summary:
        //     Provides the implementation of setting a member.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   value:
        //     The value to set.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TrySetMember(SetMemberBinder binder, object value);
        //
        // Summary:
        //     Provides the implementation of performing a unary operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   result:
        //     The result of the operation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryUnaryOperation(UnaryOperationBinder binder, out object result);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;

namespace CustomDyamicObject
{
  class Program
  {
      static void Main(string[] args)
      { //Custom Dynamic Object
          dynamic bag = new Bag();
          bag.Name = "Hello C#";
          bag.Age = 12;
          Console.WriteLine("{0}-{1}", bag.Name, bag.Age);
          Action<dynamic> hi = (self) => Console.WriteLine("Hello from {0}", self.Name);
          bag.SayHi = hi;
          bag.SayHi();
          Console.ReadLine();
      }
  }
  public class Bag : DynamicObject
  {
      Dictionary<string, object> _data = new Dictionary<string, object>();
      public override bool TryGetMember(GetMemberBinder binder, out object result)
      {
          result = _data[binder.Name];
          return true;

      }
      public override bool TrySetMember(SetMemberBinder binder, object value)
      {
          _data[binder.Name] = value;
          return true;

      }

      public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
      {
          dynamic target = _data[binder.Name];
          int length = args.Length;
          if (length == 0)
          {
              target(this);
              result = true;
              return true;
          }
          else if (length == 1)
          {
              target(this, args[1]);

              result = true;
              return true;

          }
          else
          {
              throw new NotImplementedException();
          }


      }
  }
}

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
    {

        static void 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();
            customer.City = "Gurgaon";
            customer.Country = "India";
            customer.FullAddress = function () {
                return this.City + "," + this.Country;
            }
            alert(customer.FullAddress());
        }

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
    {

        static void 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();

        }
        public static void 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 first.
  • Non-optional parameters must still be specified when you call a method.
  • Parameters are evaluated in the order they are declared.
  • If two function signatures are equally valid for your input, then the one with no optional values is given precedence.