Take() in Linq C#

In Linq i.e. System.Linq, Take operator is used to get the first specified number of elements a sequence.

Linq Take() example

using System.Linq;
protected void Page_Load(object sender, EventArgs e)
        {
            var numArray = new int[5];
            numArray[0] = 95;
            numArray[1] = 66;
            numArray[2] = 3;
            numArray[3] = 54;
            numArray[4] = 2;


            var numbers = numArray.Take(3);
            foreach (var number in numbers)
            {
                Console.WriteLine(number);
            }
        }
//It will print 95, 66, 3.

So in above sample code of Take() we have numArray.Take(3) that means it will return us the sequence of first three elements from array.

AsEnumerable() in Linq

AsEnumerable() method in Linq is used to cast or convert given type into it's IEnumerable type. AsEnumerable() basically changes the compile time type of given type that implements IEnumerable to IEnumerable itself.

Sample code to use AsEnumerable() in Linq

 protected void Page_Load(object sender, EventArgs e)
  {
      var numArray = new int[5];
      numArray[0] = 5;
      numArray[1] = 10;
      numArray[2] = 7;
      numArray[3] = 9;
      numArray[4] = 1;

      var numbers = numArray.AsEnumerable();
      foreach (var number in numbers)
       {
          Console.WriteLine(number);
       }
  }

Convert ToList() in Linq

In C# Linq, there is .ToList() extension method that is used to convert IEnumerable to List of type. Like .ToArray(), ToList() also forces immediate query execution and stores query result in List.

Example that shows how to convert array to list

 protected void Page_Load(object sender, EventArgs e)
  {
     string[] language = { "C#", "C++", "Java", "Pascal", "Cobol" };
     List languageList = language.ToList();

     foreach (string lang in languageList)
     {
                Console.WriteLine(lang);
     }
  }

Convert ToArray in linq

In C# while using Linq, we have .ToArray() extension method that is used to convert IEnumerable to an array. .ToArray() forces immediate query execution and stores query result in an array.

Example of Linq .ToArray()

 public partial class LinqToArray : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            var carslist =
                new List 
                        { new Cars { Company = "Maruti Suzuki", Average = 15.2 },
                          new Cars { Company = "Mercedes", Average = 18.7 },
                          new Cars { Company = "Volvo", Average = 20.0 },
                          new Cars { Company = "Hundai", Average = 12.8 } };

            var companies = carslist.Where(c => c.Average > 15)
                                         .Select(c => c.Company)
                                         .ToArray();

            foreach (var company in companies)
            {
                Console.WriteLine(company);
            }
        }

    public class Cars
    {
        public string Company { get; set; }
        public double Average { get; set; }
    }

Output:
   /*
     //Maruti Suzuki
     // Mercedes
     // Volvo
   */

In above sample code we have converted List to array using linq.

ASP.NET CompareValidator

In this post we will see how to use compare validator to compare the two input values. Using compare validator we can compare two values from two different input controls or we can compare input value with some constant or fixed value.

Example of compare validator

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ul style="list-style-type: none">
            <li>
                <asp:TextBox ID="txt1" runat="server" />
                =
                <asp:TextBox ID="txt2" runat="server" />
            </li>
            <li>
                <asp:Button ID="Button1" Text="Validate" runat="server" />
            </li>
        </ul>
        <br>
        <asp:CompareValidator ID="compareval" Display="dynamic" ControlToValidate="txt1"
            ControlToCompare="txt2" ForeColor="red" Type="String" EnableClientScript="false"
            Text="Values are not equal." runat="server" />
    </div>
    </form>
</body>
</html>

So in compare validator we need to set ControlToValidate and ControlToCompare in order to compare two input values.

RangeValidator to validate data in between | asp.net

From the set of validation server controlin asp.net we will see how to use RangeValidator in this post.

RangeValidator is used to check if values entered are in between specific range or not. In order to use RangeValidator, we need to add server control on web form.

RangeValidator example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter a number between 0 and 5:
        <br>
        <asp:TextBox ID="txtNumber" runat="server" />
        <asp:RangeValidator ID="RangeValidator1" ControlToValidate="txtNumber" MinimumValue="0"
            MaximumValue="5" Type="Integer" Text="The number should be in between 0 to 5."
            ForeColor="red" runat="server" />
        <br>
        <asp:Button ID="Button1" Text="Submit" runat="server" />
    </div>
    </form>
</body>
</html>

In order to rangevalidator to be work we need to set few properties: 1. Minimum value
2. Maximum value
3. Control to validate
4. Type of data i.e. Interger, Date...etc.
5. And the Text for error message

jQuery auto focus.

In this post we will see how to set focus automatically on input control. This is done using .focus() function in jQuery.

jQuery auto focus example

<script type="text/javascript">
   $(function () {
        $("#fName").focus();
   });
</script>

.focus()function is simple and we can call it on input control on which we need to set focus.

Below is simple full example of .focus() in jQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#fName").focus();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="fName"/>
<input type="text" id="lName"/>
</div>
</form>
</body>
</html>

Using RequiredFieldValidator to validate controls | asp.net

In ASP.NET there exists a set of validation server control which are useful to validate the data on form. In this post we will see how to use RequiredFieldValidator.

RequiredFieldValidator is used to check if field on the form is not empty. In order to use RequiredFiledValidator, we need to add server control on web form. After adding control on page we need to associate the RequiredFieldValidator control to the control that we have to validate. e.g. Textbox. Also we need to set error message to show when validation fails.

RequiredFieldValidator example

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Name:<br />
        <asp:TextBox runat="server" ID="Name" />
        <asp:RequiredFieldValidator runat="server" ID="validateName" ControlToValidate="Name"
            ErrorMessage="Enter the name." ForeColor="Red" />
        <br />
        <br />
        <asp:Button runat="server" ID="btnSubmit" Text="Ok" OnClick="Post_Page" CausesValidation="" />
    </div>
    </form>
</body>
</html>

Here you will notice that the validation is happening at client side means without postback, this is because by default validator control does client side validation if browser supports DHTML. And if browser does not supports scripting then it will do server side validation, means page will postback and it will check for "Page.IsValid()" and then will return true or false.

And if we explicitly want to do the server side validation then we need to set EnableClientScript="false"

Detect IE browser | jQuery

In previous post we saw how to get IE browser in JavaScript
In this post we wiil see how to detect IE browser using jQuery. jQuery have Browser object like Navigator object in JavaScript. And using Browser object we can get Browser name, version..etc.
jQuery to get IE browser
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title></title>
</head>
<script type="text/javascript">
    function getBrowser() {
    
        if ($.browser.msie) {
            alert('Detected IE browser');
        }
    }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" onclick="getBrowser();" value="Get Browser Name"/>
    </div>
    </form>
</body>
</html>

Output This will show alert message Detected IE browser.

Detect IE browser | Javascript

While working with Web projects those required cross browser compatibility we often need to detect the browser type,like ie, Firefox Mozilla, or chrome...etc.

In this post we will see how to find ie browser. This is done using navigator object in JavaScript. Navigator has appName property that we can use to find ie browser.

JavaScript to detect ie

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<script type="text/javascript">
    function getBrowserName()
    {
        if(navigator.appName=="Microsoft Internet Explorer") {
            alert("This is " + navigator.appName + " Browser");
        }
  }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" onclick="return getBrowserName();" value="Get Browser Name"/>
    </div>
    </form>
</body>
</html>

//Above code will show alert message "This is Microsoft Internet Explorer Browser"

Here we will see how to detect IE browser using jQuery