Skip to main content

Posts

Showing posts with the label C#

How to implement Stack using linked list

Stacks are easier to implement using linked lists. There is no need to set a limit on the size of the stackusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LinkedlistUsingStack { public class Node { public int Data { get; set; } public Node Next { get; set; } public Node(int data) { this.Data = data; } } public class Stack { private Node _stackTop; public void Push(int newValue) { Node newNode = new Node(newValue); newNode.Next = _stackTop; _stackTop = newNode; } public bool IsEmpty() { return _stackTop == null; } public int Pop() { Node temp = _stackTop; var data = temp.Data; _stackTop = temp.Next; return data; } public void Print() { …

How to Find if Linked List contains Loops or Cycles in C#

In this post I will show you how to detect loop in linked list.We can find the loop in the linked list via Floyd’s Cycle-Finding Algorithm, explained here.The algorithm is pretty straightforward: We start at the beginning of the linked list with two pointers. The first pointer is incremented through each node of the list. The second pointer moves twice as fast, and skips every other node. If the linked list contains a loop, these two pointers will eventually meet at the same node, thus indicating that the linked list contains a loop. .using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algo { public class Node { public Node Next { get; set; } public int Value { get; set; } public Node(int value) { this.Value = value; } } public class LinkedList { private Node _head; public LinkedList() { } public vo…

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 check a tree is a binary tree of not

This is continuation of my post How to create binary tree in c#.In this post I will show you how to check a given tree is a binary tree or not. public bool isBST() { return (IsBST(_root)); } private bool IsBST(Node node) { if (node == null) return (true); // do the subtrees contain values that do not // agree with the node? if (node.Left != null && FindMaxValue(node.Left) > node.Data) return (false); if (node.Right != null && FindMinValue(node.Right) <= node.Data) return (false); // check that the subtrees themselves are ok return (IsBST(node.Left) && IsBST(node.Right)); }

Mirror of a binary tree

This is continuation of my post How to create binary tree in c#.In this post I will show you how convert a given binary tree into it’s mirror image./**
Changes the tree into its mirror image. So the tree...
       4
      / \
     2   5
    / \
   1   3 is changed to...
       4
      / \
     5   2
        / \
       3   1Strategy:Uses a recursive helper that recurs over the tree, swapping the left/right pointers. public void MirrorTree() { MirrorTree(_root); } private void MirrorTree(Node node) { if (node != null) { // do the sub-trees MirrorTree(node.Left); MirrorTree(node.Right); // swap the left/right pointers Node temp = node.Left; node.Left = node.Right; node.Right = temp; } }

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…

Given a binary tree, find path sum

Given a tree and a sum, returns true if there is a path from the root  down to a leaf, such that adding up all the values along the path  equals the given sum.let’s consider the following binary tree as an example and path sum value is 9.        4
      / \
     2   5
    / \
   1   3Root-to-leaf paths:
   path 1: 4 2 1
   path 2: 4 2 3
   path 3: 4 5You can see that there are two path that gives sum 9 (Path2 and Path 3).Traverse the tree from root to leaves in top down fashion and subtract the node value from the sum  and check to see if the sum is 0 when you run out of tree. public bool HasPathSum(int sum) { return HasPathSum(_root, sum); } private bool HasPathSum(Node root, int sum) { // return true if we run out of tree and sum==0 if (root == null) return sum == 0; else { int subSum = sum - root.Data; return ( HasPathSum(root.L…

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 convert DataSet to List

In this post I am going to show you a very useful c# code snippet that convert DataSet to List<T>. public static List<T> ToCollection<T>(this DataTable dt) { List<T> lst = new List<T>(); Type tClass = typeof(T); PropertyInfo[] pClass = tClass.GetProperties(); List<DataColumn> dc = dt.Columns.Cast<DataColumn>().ToList(); T cn; foreach (DataRow item in dt.Rows) { cn = (T)Activator.CreateInstance(tClass); foreach (PropertyInfo pc in pClass) { DataColumn d = dc.Find(c => c.ColumnName == pc.Name); if (d != null) { if (item[pc.Name] != DBNull.Value) { pc.SetValue(cn, (item[pc.Name]), null); } } } …

Self host web API

In this post I will show you how to create web api that run outside IIS application.
Open visual studio and create a console application

Add the Web API and OWIN Packages From the Tools menu, click Library Package Manager, then click Package Manager Console. In the Package Manager Console window, enter the following command:
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

Right click  the project and add new class named Startup.cs and add following code snippet in it
public class Startup { // This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. public void Configuration(IAppBuilder appBuilder) { // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", default…

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 to post data using HttpClient

In this post I will show you how to post data to web api using HttpClient.

privatestatic async Task PostJSON() { HttpClient httpClient = new HttpClient(); HttpContent content = new StringContent(@"{ ""Username"": """ + "etc." + @"""}"); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await httpClient.PostAsync("http://myapi.com/authentication", content); string statusCode = response.StatusCode.ToString(); } /// <summary>/// Post Key/Value/// </summary>/// <returns></returns>privatestatic async Task Post() { HttpClient client = new HttpClient(); var values = new Dictionary<string, string>(); values.Add("author", "santosh"); values.Add(…

How to check stream has Image or not

Let's suppose you have a page on which user upload there image and you want to validate that user is uploading image file only not other file format.The one easy solution is use regex and validate the extension of the file but if user rename the extension of the file and upload some executable code.Following is the simple c# code snippet that check the file type by the header value.
privatebool IsImage() { bool isImage = false; FileStream stream = new FileStream(Server.MapPath(@"Images\a.txt"), FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(stream); // Read the first 25 characters, we will be checking for a GIF or JPG signature.char[] strBuffer = newchar[25]; reader.ReadBlock(strBuffer, 0, 25); string stringBuffer = newstring(strBuffer); // Is this an image?if (stringBuffer.IndexOf("GIF8") &gt; -1 || stringBuffer.IndexOf("JFIF") &gt; -1) { i…

How To Convert HTML to Text, Easily

Whether you want to convert an HTML page into pure text so you can parse out that special piece of information, or you simply want to load a page from the Net into your own word processing package, this mini function could come in handy. It’s called StripTags and accepts an HTML string. Using a regular expression, it identifies all <tags>, removes them, and returns the modified string. Here’s the code: <%@ Page Language="C#" ValidateRequest="False" AutoEventWireup="true" CodeFile="StripTag.aspx.cs" Inherits="StripTag" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title>Untitled Page</title></head><body><formid="form1"runat="server"><div><asp:TextBoxID="TextBox1&quo…

Decorator Design Pattern

Intent:
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality (also known as Wrapper)





using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DecoratorPattern { publicclass UpperStream : Stream { private Stream _stream; public UpperStream(Stream stream) { this._stream = stream; } publicoverridelong Length { get { return _stream.Length; } } publicoverrideint Read(byte[] buffer, int offset, int count) { var numberOfBytesRead = _stream.Read(buffer, offset, count); for (int i = 0; i < numberOfBytesRead; i++) { buffer[i] = (byte)char.ToUpper((char)((int)buffer[i])); } return numberOfBytesRead; } publicoverrideboo…

Strategy Design Pattern

Strategy Design Pattern
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Problem:
Client wants to decide at run-time what serialization it should use to serialize a type. Many different serialization algorithms are already available.
Solution:
Encapsulate the different serialization algorithms using the Strategy pattern!
C# Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StrategyPattern { publicinterface ISerializer { void Serialize(); } publicclass XmlSerializer : ISerializer { publicvoid Serialize() { Console.WriteLine("Xml serilizer Invoked"); } } publicclass JsonSerializer : ISerializer { publicvoid Serialize() { Console.WriteLine("Json serializer Invoked"); } }�…