Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Tuesday, 18 October 2016

How to: Group Query Results (C# Programming Guide)

Grouping is one of the most powerful capabilities of LINQ. The following examples show how to group data in various ways:

  • By a single property.
  • By the first letter of a string property.
  • By a computed numeric range.
  • By Boolean predicate or other expression.
  • By a compound key.
In addition, the last two queries project their results into a new anonymous type that contains only the student's first and last name. For more information, see the group clause (C# Reference).

Example

All the examples in this topic use the following helper classes and data sources.
public class StudentClass
{
    #region data
    protected enum GradeLevel { FirstYear = 1, SecondYear, ThirdYear, FourthYear };
    protected class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int ID { get; set; }
        public GradeLevel Year;
        public List<int> ExamScores;
    }

    protected static List<Student> students = new List<Student>
    {
        new Student {FirstName = "Terry", LastName = "Adams", ID = 120, 
            Year = GradeLevel.SecondYear, 
            ExamScores = new List<int>{ 99, 82, 81, 79}},
        new Student {FirstName = "Fadi", LastName = "Fakhouri", ID = 116, 
            Year = GradeLevel.ThirdYear,
            ExamScores = new List<int>{ 99, 86, 90, 94}},
        new Student {FirstName = "Hanying", LastName = "Feng", ID = 117, 
            Year = GradeLevel.FirstYear, 
            ExamScores = new List<int>{ 93, 92, 80, 87}},
        new Student {FirstName = "Cesar", LastName = "Garcia", ID = 114, 
            Year = GradeLevel.FourthYear,
            ExamScores = new List<int>{ 97, 89, 85, 82}},
        new Student {FirstName = "Debra", LastName = "Garcia", ID = 115, 
            Year = GradeLevel.ThirdYear, 
            ExamScores = new List<int>{ 35, 72, 91, 70}},
        new Student {FirstName = "Hugo", LastName = "Garcia", ID = 118, 
            Year = GradeLevel.SecondYear, 
            ExamScores = new List<int>{ 92, 90, 83, 78}},
        new Student {FirstName = "Sven", LastName = "Mortensen", ID = 113, 
            Year = GradeLevel.FirstYear, 
            ExamScores = new List<int>{ 88, 94, 65, 91}},
        new Student {FirstName = "Claire", LastName = "O'Donnell", ID = 112, 
            Year = GradeLevel.FourthYear, 
            ExamScores = new List<int>{ 75, 84, 91, 39}},
        new Student {FirstName = "Svetlana", LastName = "Omelchenko", ID = 111, 
            Year = GradeLevel.SecondYear, 
            ExamScores = new List<int>{ 97, 92, 81, 60}},
        new Student {FirstName = "Lance", LastName = "Tucker", ID = 119, 
            Year = GradeLevel.ThirdYear, 
            ExamScores = new List<int>{ 68, 79, 88, 92}},
        new Student {FirstName = "Michael", LastName = "Tucker", ID = 122, 
            Year = GradeLevel.FirstYear, 
            ExamScores = new List<int>{ 94, 92, 91, 91}},
        new Student {FirstName = "Eugene", LastName = "Zabokritski", ID = 121,
            Year = GradeLevel.FourthYear, 
            ExamScores = new List<int>{ 96, 85, 91, 60}}
    };
    #endregion

    //Helper method, used in GroupByRange.
    protected static int GetPercentile(Student s)
    {
        double avg = s.ExamScores.Average();
        return avg > 0 ? (int)avg / 10 : 0;
    }



    public void QueryHighScores(int exam, int score)
    {
        var highScores = from student in students
                         where student.ExamScores[exam] > score
                         select new {Name = student.FirstName, Score = student.ExamScores[exam]};

        foreach (var item in highScores)
        {
            Console.WriteLine("{0,-15}{1}", item.Name, item.Score);
        }
    }
}

public class Program
{
    public static void Main()
    {
        StudentClass sc = new StudentClass();
        sc.QueryHighScores(1, 90);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}

Example

The following example shows how to group source elements by using a single property of the element as the group key. In this case the key is a string, the student's last name. It is also possible to use a substring for the key. The grouping operation uses the default equality comparer for the type.
Paste the following method into the StudentClass class. Change the calling statement in the Main method to sc.GroupBySingleProperty().
public void GroupBySingleProperty()
{
    Console.WriteLine("Group by a single property in an object:");

    // Variable queryLastNames is an IEnumerable<IGrouping<string, 
    // DataClass.Student>>. 
    var queryLastNames =
        from student in students
        group student by student.LastName into newGroup
        orderby newGroup.Key
        select newGroup;

    foreach (var nameGroup in queryLastNames)
    {
        Console.WriteLine("Key: {0}", nameGroup.Key);
        foreach (var student in nameGroup)
        {
            Console.WriteLine("\t{0}, {1}", student.LastName, student.FirstName);
        }
    }
}
/* Output:
    Group by a single property in an object:
    Key: Adams
            Adams, Terry
    Key: Fakhouri
            Fakhouri, Fadi
    Key: Feng
            Feng, Hanying
    Key: Garcia
            Garcia, Cesar
            Garcia, Debra
            Garcia, Hugo
    Key: Mortensen
            Mortensen, Sven
    Key: O'Donnell
            O'Donnell, Claire
    Key: Omelchenko
            Omelchenko, Svetlana
    Key: Tucker
            Tucker, Lance
            Tucker, Michael
    Key: Zabokritski
            Zabokritski, Eugene
*/

Example

The following example shows how to group source elements by using something other than a property of the object for the group key. In this example, the key is the first letter of the student's last name.
Paste the following method into the StudentClass class. Change the calling statement in the Main method to sc.GroupBySubstring().
public void GroupBySubstring()
{            
    Console.WriteLine("\r\nGroup by something other than a property of the object:");

    var queryFirstLetters =
        from student in students
        group student by student.LastName[0];

    foreach (var studentGroup in queryFirstLetters)
    {
        Console.WriteLine("Key: {0}", studentGroup.Key);
        // Nested foreach is required to access group items.
        foreach (var student in studentGroup)
        {
            Console.WriteLine("\t{0}, {1}", student.LastName, student.FirstName);
        }
    }           
}
/* Output:
    Group by something other than a property of the object:
    Key: A
            Adams, Terry
    Key: F
            Fakhouri, Fadi
            Feng, Hanying
    Key: G
            Garcia, Cesar
            Garcia, Debra
            Garcia, Hugo
    Key: M
            Mortensen, Sven
    Key: O
            O'Donnell, Claire
            Omelchenko, Svetlana
    Key: T
            Tucker, Lance
            Tucker, Michael
    Key: Z
            Zabokritski, Eugene
*/

Example

The following example shows how to group source elements by using a numeric range as a group key. The query then projects the results into an anonymous type that contains only the first and last name and the percentile range to which the student belongs. An anonymous type is used because it is not necessary to use the complete Student object to display the results. GetPercentile is a helper function that calculates a percentile based on the student's average score. The method returns an integer between 0 and 10.
//Helper method, used in GroupByRange.
protected static int GetPercentile(Student s)
{
    double avg = s.ExamScores.Average();
    return avg > 0 ? (int)avg / 10 : 0;
}
Paste the following method into the StudentClass class. Change the calling statement in the Main method to sc.GroupByRange().
public void GroupByRange()
{            
    Console.WriteLine("\r\nGroup by numeric range and project into a new anonymous type:");

    var queryNumericRange =
        from student in students
        let percentile = GetPercentile(student)
        group new { student.FirstName, student.LastName } by percentile into percentGroup
        orderby percentGroup.Key
        select percentGroup;

    // Nested foreach required to iterate over groups and group items.
    foreach (var studentGroup in queryNumericRange)
    {
        Console.WriteLine("Key: {0}", (studentGroup.Key * 10));
        foreach (var item in studentGroup)
        {
            Console.WriteLine("\t{0}, {1}", item.LastName, item.FirstName);
        }
    }            
}
/* Output:
    Group by numeric range and project into a new anonymous type:
    Key: 60
            Garcia, Debra
    Key: 70
            O'Donnell, Claire
    Key: 80
            Adams, Terry
            Feng, Hanying
            Garcia, Cesar
            Garcia, Hugo
            Mortensen, Sven
            Omelchenko, Svetlana
            Tucker, Lance
            Zabokritski, Eugene
    Key: 90
            Fakhouri, Fadi
            Tucker, Michael
*/

Example

The following example shows how to group source elements by using a Boolean comparison expression. In this example, the Boolean expression tests whether a student's average exam score is greater than 75. As in previous examples, the results are projected into an anonymous type because the complete source element is not needed. Note that the properties in the anonymous type become properties on the Key member and can be accessed by name when the query is executed.
Paste the following method into the StudentClass class. Change the calling statement in the Main method to sc.GroupByBoolean().
public void GroupByBoolean()
{            
    Console.WriteLine("\r\nGroup by a Boolean into two groups with string keys");
    Console.WriteLine("\"True\" and \"False\" and project into a new anonymous type:");
    var queryGroupByAverages = from student in students
                               group new { student.FirstName, student.LastName }
                                    by student.ExamScores.Average() > 75 into studentGroup
                               select studentGroup;

    foreach (var studentGroup in queryGroupByAverages)
    {
        Console.WriteLine("Key: {0}", studentGroup.Key);
        foreach (var student in studentGroup)
            Console.WriteLine("\t{0} {1}", student.FirstName, student.LastName);
    }            
}
/* Output:
    Group by a Boolean into two groups with string keys
    "True" and "False" and project into a new anonymous type:
    Key: True
            Terry Adams
            Fadi Fakhouri
            Hanying Feng
            Cesar Garcia
            Hugo Garcia
            Sven Mortensen
            Svetlana Omelchenko
            Lance Tucker
            Michael Tucker
            Eugene Zabokritski
    Key: False
            Debra Garcia
            Claire O'Donnell
*/

Example

The following example shows how to use an anonymous type to encapsulate a key that contains multiple values. In this example, the first key value is the first letter of the student's last name. The second key value is a Boolean that specifies whether the student scored over 85 on the first exam. You can order the groups by any property in the key.
Paste the following method into the StudentClass class. Change the calling statement in the Main method to sc.GroupByCompositeKey().
public void GroupByCompositeKey()
{

    var queryHighScoreGroups =
        from student in students
        group student by new { FirstLetter = student.LastName[0], 
            Score = student.ExamScores[0] > 85 } into studentGroup
        orderby studentGroup.Key.FirstLetter
        select studentGroup;

    Console.WriteLine("\r\nGroup and order by a compound key:");
    foreach (var scoreGroup in queryHighScoreGroups)
    {
        string s = scoreGroup.Key.Score == true ? "more than" : "less than";
        Console.WriteLine("Name starts with {0} who scored {1} 85", scoreGroup.Key.FirstLetter, s);
        foreach (var item in scoreGroup)
        {
            Console.WriteLine("\t{0} {1}", item.FirstName, item.LastName);
        }
    }
}
/* Output:
    Group and order by a compound key:
    Name starts with A who scored more than 85
            Terry Adams
    Name starts with F who scored more than 85
            Fadi Fakhouri
            Hanying Feng
    Name starts with G who scored more than 85
            Cesar Garcia
            Hugo Garcia
    Name starts with G who scored less than 85
            Debra Garcia
    Name starts with M who scored more than 85
            Sven Mortensen
    Name starts with O who scored less than 85
            Claire O'Donnell
    Name starts with O who scored more than 85
            Svetlana Omelchenko
    Name starts with T who scored less than 85
            Lance Tucker
    Name starts with T who scored more than 85
            Michael Tucker
    Name starts with Z who scored more than 85
            Eugene Zabokritski
*/

Monday, 17 October 2016

Create Table Programmatically in ASP.NET

In this article we will create a table in a web application programmatically. Instead of a database table we will create a table in a code behind file using the DataTable class. We can add rows in this table dynamically from front ends through user input as many as we want. Basically this technique is used for adding and showing temporary data at run time.
All the code related to this mini application is given below. So let's start to create this web application.
Step 1: Open Visual Studio 2010.
  • Go to Visual Studio 2010
  • New-> Select a website application
  • Click OK
img1.gif
Step 2: Now we will add a new aspx page to our project; do the following for that:
  • Go to the Solution Explorer
  • Right-click on the Project name
  • Select add new item
  • Add new web page and give it a name
  • Click OK
img2.gif
Step 3: This is the code of the .aspx file that determines how our page looks:
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs"Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

<body style=" background-color:Yellow">
    <form id="form1" runat="server">
    <div >
  
   <asp:gridview runat="server" ID="Gv1" AutoGenerateColumns="true" HeaderStyle-BackColor="Red" BackColor="LightBlue"
    BorderWidth="5" BorderColor="Blue">
   </asp:gridview>
    </div>
    <div>
    <h1>Add New Row.....</h1>
        Product NO:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:TextBox ID="txtb1" runat="server"></asp:TextBox>
        <br />
        Product Name:&nbsp;
     <asp:TextBox ID="txtb2" runat="server"></asp:TextBox>
        <br />
        Order Date:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <asp:TextBox ID="txtb3" runat="server"></asp:TextBox>
      &nbsp;<asp:Label runat="server" Text="dd/mm/yyyy"></asp:Label>
        <br />
        Quantity:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
       <asp:TextBox ID="txtb4" runat="server"></asp:TextBox>
        <br />
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
       <asp:Button runat="server" OnClick="Addnewrow" Text="Add Row" />
    </div>
    </form>
</body>
</html>

 Step 4: This is the code behind file code. It contains the logic of application:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class Default2 : System.Web.UI.Page
{
    DataTable tb = new DataTable();
    DataRow dr;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        createtable();
      

    }
    public void createtable()
    {
       
        tb.Columns.Add("Prod_NO"typeof(string));
        tb.Columns.Add("Prod_Name"typeof(string));
        tb.Columns.Add("Order_Date"typeof(string));
        tb.Columns.Add("Quantity"typeof(string));

       dr = tb.NewRow();
        dr["Prod_NO"] = "101";
        dr["Prod_Name"] = "Product1";
        dr["Order_Date"] = "12/06/2012";
        dr["Quantity"] = "50";
        tb.Rows.Add(dr);

        dr = tb.NewRow();
        dr["Prod_NO"] = "102";
        dr["Prod_Name"] = "Product2";
        dr["Order_Date"] = "15/06/2012";
        dr["Quantity"] = "70";
        tb.Rows.Add(dr);
        Gv1.DataSource = tb;
        Gv1.DataBind();
        ViewState["table1"] = tb;
    }

    protected void Addnewrow(object sender, EventArgs e)
    {
        tb =(DataTable) ViewState["table1"];
        dr = tb.NewRow();
        dr["Prod_NO"] = txtb1.Text;
        dr["Prod_Name"] = txtb2.Text;
        dr["Order_Date"] = txtb3.Text;
        dr["Quantity"] = txtb4.Text;
        tb.Rows.Add(dr);
        Gv1.DataSource = tb;
        Gv1.DataBind();
        txtb1.Text = "";
        txtb2.Text = "";
        txtb3.Text = "";
        txtb4.Text = "";
    }
}

Step 5: After running the application, it look like this:

img3.gif
To add a new row you will fill in all the text boxes and click the Add Row button:
img4.gif
Now you can see one row added in the GridView:

img5.gif

Thursday, 13 October 2016

Anonymous Methods C#

https://www.youtube.com/watch?v=drgsIO5M8ok

See our other step by step video series below.
Learn MVC 5 in 16 hours:- https://goo.gl/dmdakg
Learn AngularJS 1.5 Step by Step in 8 hours :- https://goo.gl/F3ovSr
Learn Angular 2.0 Step by Step in 8 hours:- http://tinyurl.com/z3vnvhg
Learn Design Pattern in 8 hours:- https://goo.gl/eJdn0m
Learn C# in 100 hours :- https://goo.gl/FNlqn3
Learn MSBI in 32 hours:- https://goo.gl/TTpFZN
Learn SharePoint Step by Step in 8 hours:- https://goo.gl/XQKHeP
Learn TypeScript in 45 Minutes :- https://goo.gl/oRkawI 

In this .NET and C# video we will see a small sample for Anonymous methods and in what situations to use anonymous methods.

For more such videos visit http://www.questpond.com

We are also distributing a 100 page Ebook ".NET Interview Questions". If you want this ebook please share this video in your facebook/twitter/linkedin account and email us on questpond@questpond.com with the shared link and we will email you the PDF.

https://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx

Anonymous Methods (C# Programming Guide)

Visual Studio 2015
 
In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide).
Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. Here are two examples:
// Create a handler for a click event.
button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };
// Create a delegate.
delegate void Del(int x);

// Instantiate the delegate using an anonymous method.
Del d = delegate(int k) { /* ... */ };
By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.
For example, specifying a code block instead of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when you start a new thread. This class creates a thread and also contains the code that the thread executes without creating an additional method for the delegate.
void StartThread()
{
    System.Threading.Thread t1 = new System.Threading.Thread
      (delegate()
            {
                System.Console.Write("Hello, ");
                System.Console.WriteLine("World!");
            });
    t1.Start();
}

Remarks

The scope of the parameters of an anonymous method is the anonymous-method-block.
It is an error to have a jump statement, such as gotobreak, or continue, inside the anonymous method block if the target is outside the block. It is also an error to have a jump statement, such as gotobreak, or continue, outside the anonymous method block if the target is inside the block.
The local variables and parameters whose scope contains an anonymous method declaration are called outer variables of the anonymous method. For example, in the following code segment, n is an outer variable:
int n = 0;
Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); };
A reference to the outer variable n is said to be captured when the delegate is created. Unlike local variables, the lifetime of a captured variable extends until the delegates that reference the anonymous methods are eligible for garbage collection.
An anonymous method cannot access the ref or out parameters of an outer scope.
No unsafe code can be accessed within the anonymous-method-block.
Anonymous methods are not allowed on the left side of the is operator.

Example

The following example demonstrates two ways of instantiating a delegate:
  • Associating the delegate with an anonymous method.
  • Associating the delegate with a named method (DoWork).
In each case, a message is displayed when the delegate is invoked.
// Declare a delegate.
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // Instantiate the delegate type using an anonymous method.
        Printer p = delegate(string j)
        {
            System.Console.WriteLine(j);
        };

        // Results from the anonymous delegate call.
        p("The delegate using the anonymous method is called.");

        // The delegate instantiation using a named method "DoWork".
        p = new Printer(TestClass.DoWork);

        // Results from the old style delegate call.
        p("The delegate using the named method is called.");
    }

    // The method associated with the named delegate.
    static void DoWork(string k)
    {
        System.Console.WriteLine(k);
    }
}
/* Output:
    The delegate using the anonymous method is called.
    The delegate using the named method is called.
*/