The Array.isArray() was released with the release of ECMAScript5 JavaScript. This method simply checks whether the argument passed to its arguments is an array or not. This article will explain this Array isArray() method by explaining its syntax and then showcasing some examples.
We will start by going over the syntax of the Array isArray() method.
Syntax Observe the syntax of the Array isArray() below:
In this syntax:
Array is the default JavaScript Array Object
Object is the argument, the one we want to determine as an array or not
Return Type
Boolean: Returns true if the object passed to this method was actually an array otherwise it would return false
Additional Information
Since this is a method of the default JavaScript Array Object, therefore it is also known as the static property of this Array Object.
Example 1: Passing an Array to Array.isArray() Method
To demonstrate the working of this method, first create an array of the same types of values with the help of the following line:
my_object = [1, 2, 3, 4, 5, 6, 7, 8, 9];
After that, pass this array to the Array.isArray() method and store the return value in a new variable named as the result:
result = Array.isArray(my_object);
After that, simply display the value inside the result variable on the terminal using the console log function:
Execute the code, and observe the output to be:
The output shows that the object passed to this method was actually an array.
Example 2: Passing an Array With Different Data Type Values
To check whether this method works with an array containing values of different data types, create an array using the following line:
Pass this object into the Array.isArray() method and store the result in a result variable:
result = Array.isArray(my_object);
Afterwards, simply print the result from the result variable onto the terminal using the console log() function:
Execute the code and observe the following output:
From the output, it is conclusive that the type of data stored inside the array doesn’t matter. It only checks whether the object is an array or not, which in this case was true.
Example 3: Passing a String Object in Array.isArray() Method
To demonstrate what happens when a non-array object is passed to the Array isArray() method, create a new string variable with the help of the following line:
string_var = «Hello World»;
Pass this string value into the arguments of the Array.isArray() method and store the outcome in a new variable:
result_var = Array.isArray(string_var);
Print the value inside the result_var on the terminal using the console log() function:
Execute the program and get the following output on the terminal:
It returns that the object passed into its argument was not an array.
Conclusion
The Array.isArray() method is pretty simple. It simply checks whether the object in its argument is an array or not and returns true or false to the caller. If an array is being passed, the values or even the data types of its values don’t matter. In this article, we have learned about the different outcomes of the Array.isArray() method with the help of different examples.
JavaScript offers numerous methods to fulfill the requirements of programmers by executing the block of code. For scheduling a timeout, JavaScript provides methods including setInterval(), setTimeout, clearTimeout(), and clearInterval(). It provides a timeout functionality that allows users to perform any operation after a specific time interval. Moreover, the piece of code is repeated after a set interval of time. These methods are useful for sensitive websites such as banking websites and e-commerce sites.
This post demonstrates the working and usage of clearTimeout() and clearInterval() methods:
How to Utilize clearTimeout() Method in JavaScript
How to Utilize clearInterval() Method in JavaScript
JavaScript clearTimeout() and clearInterval() Methods
In JavaScript, the clearTimeout() and clearInterval() methods are used to clear the timer that was initialized using the setInterval() and setTimeout() methods, respectively. The clearTimeout() method cancels the timeout that was earlier set by the setTimeout(). The same procedure is applied using clearInterval() to antipara the time interval fixed by setInterval().
How to Utilize the clearTimeout() Method in JavaScript?
The clearInterval() method is utilized to stop the execution that started with the setTimeout() method. The method takes the same variable name that was returned by the setTimeout() method. The syntax of the clearTimeout() method is provided here:
Syntax
The timeoutID is the value of the timer set by the setTimeout() method. It is a mandatory field.
Example
An example is explained with the usage of the clearTimeout() method in JavaScript.
Code
<html> <body> <h2> An example of using the clearTimeout() method in JavaScript</h2> <button onclick=«startCount()»>Press Button to Start counter</button> <input type=«text»id=«txt»> <button onclick=«stopCount()»>Press Button to Stop counter</button> <script> var timer = 0; var time; var counter = 0; function timedCount(){ document.getElementById(«txt»).value = counter; counter = counter + 1; time = setTimeout(timedCount, 1000);} function startCount(){ if(!timer){ timer = 1; timedCount();}} function stopCount(){ clearTimeout(time); timer = 0;} </script> </body> </html>
In the above code, the clearTimeout() method is utilized with the setTimeout() method to differentiate the working process between them. The description is provided in the listed format:
Firstly, a button “Press Button to Start counter” is attached with a startCount() method.
Another button is associated with the stopCount() method to stop the execution of the above method.
After pressing the button, the counter variable is initialized and incremented by one every 1000 milliseconds.
These values are stored in the time variable that is utilized to stop the counter by passing it to the clearTimeout() method.
The screenshot of the above code is as follows:
Output
It is observed that the counter starts after pressing the “Press Button to Start counter” button. The counter increments the value by adding one. The process is continued until the “Press Button to Stop counter” button is pressed.
How to Utilize the clearInterval() Method in JavaScript?
This method clears the schedule created by the setInterval() method. The execution of the created timer is finished by passing the same variable that was returned from the setInterval() method. The following syntax refers to the setInterval() method.
Syntax
clearInterval(intervalID)
In this syntax, the intervalID is the passing variable that utilizes the same value as the setInterval() method.
Example The example code written below refers to the clearTimeout() method in JavaScript.
Code
<h2> An example of using the clearInterval() method in JavaScript</h2> <p>Press Button to start an interval that prints a message. </p> <button id=«btn»onclick=«Result()»>Press Button to Start Interval</button> <button id=«antipara»>Press Button to antipara interval</button> <div id=«output»></div> <script> function Result(){ document.getElementById(‘antipara’).addEventListener(‘click’, () =>{ cancelInterval()}) const intervalID = setInterval(() =>{ document.getElementById(‘output’).textContent += «Is JavaScript a Scripting Language ? «; },500); function cancelInterval(){ clearInterval(intervalID); document.getElementById(‘output’).textContent = » Cancelled Interval !»; } } </script>
The code is described as:
Two buttons are associated with the methods.
The Result() method is employed with a button “Press Button to Start Interval”.
First, the interval is set by the setInterval() method.
After that, a message asking, “Is JavaScript a scripting language?” is displayed every 500 milliseconds.
In the end, the clearInterval() method is used by passing the same variable returned by the setInterval() method.
Output
In the output, the message “Is JavaScript a scripting language?” is displayed repeatedly by pressing the Start Interval button. After that, the clearInterval() method is utilized to stop the execution and display a message “Canceled Interval”.
Conclusion
JavaScript provides functionality to stop the execution of code by utilizing the clearTimeout() and clearInterval() methods. The clearTimeout() method is employed to clear the timer value set by the setTimeout() method. On the other hand, the clearInterval() method stops the interval by passing the same value set by the setInterval() method in JavaScript. Here, you have learned to understand the clearTimeout() and clearInterval() methods in JavaScript.
The window scrollTo method is used to scroll the browser window to a specific coordinate. This method is named the scrollTo() while the window is the Window Object. A browser window that is open is represented by the window object. To better understand this method, quickly go over the syntax given below:
Syntax of the scrollTo() Method
window.scrollTo(X-coordinate, Y-coordinate);
In this syntax:
window is the browser’s window Object.
X-coordinate is the horizontal displacement to the browser’s window at.
Y-coordinate is the derecho displacement to pan the browser’s window at.
Demonstration of the Window scrollTo() Method
To demonstrate the working of the scrollTo method, start by creating an HTML file with the following lines:
<center> <b class=«scrolled»>I am Placed at 4000px Vertically</b> <button onclick=«clicked()»>Click me to scroll down</button> </center>
In this above HTML code snippet,
A bold tag was created with some text inside it with the class being scrolled. This class will be used to place this tag at 4000px with the help of CSS.
A button was created which calls the clicked() function in the JavaScript file.
After that is done, we want to add the following lines to the CSS of our webpage:
The height of the body tag is set to 7000px so the webpage becomes scrollable even without having more elements on it.
The bold tag with the class scrolled has been placed at 4000px.
Executing the webpage now provides us the following output on the browser’s window:
As you can see from the output, to visit the bold tag, one must manually scroll the browser’s window.
To add functionality to the button so that it scrolls us directly on the bold tag with text, write the following lines in the script file:
function clicked(){ window.scrollTo(0, 4000); }
In these lines, the function clicked() is created, which is called upon pressing the button, and in this function, we are simply passing the Y-coordinate as 4000px to the window scrollTo() method. This provides the following outcome on the HTML webpage:
As it is clearly shown in the output, pressing the button pans the browser’s window to 4000px vertically.
Wrap up
The window scrollTo() method is used to call the browser’s window object and then pan the browser’s window to a specific position by passing in the x and y coordinates in its arguments. This article demonstrated the working of the window scrollTo() method with the help of an example.
The JavaScript Date.getTime() method extracts the numerical number in milliseconds since January 1st, 1970. The method always utilizes the Universal Time Coordinated (UTC) format to represent the time.
If you are not accesible with the getTime() method in JavaScript, it is the best place to learn and understand this method. We have compiled this guide to provide a brief overview of the working and usage of the Date.getTime() method.
How to Use the Date getTime() Method in JavaScript?
The getTime() returns the milliseconds based on the regional time for a specified date. Users can use the date object to call the getTime() method in JavaScript. Moreover, users can utilize it to assign the time and date to another date object in JavaScript.
The syntax of the getTime() method in JavaScript is as follows:
Syntax
The Date is the object that saves information about the time and date. The getTime() method will not accept parameters and returns the integer value, which is equal to the number of milliseconds.
Example 1: Retrieve the Time From a Specific Date/Time
In the example code, we are using the Date.getTime() method to retrieve the time from the user-defined time in milliseconds.
Code
<script> // An example for using the getTime() method // While creating Date object var date1 = new Date(‘December 24, 2000 04:25:52’); // The information for milliseconds is // extracted using getTime() var date2 = date1.getTime(); // Display timein milliseconds. document.write(date2); </script>
In the above code:
The date1 is the variable that stores the date/time information.
After that, the getTime() method is used to extract the milliseconds that are stored in the date1 variable. The extracted time is stored in the date2 object.
Finally, the value stored in the date2 object is displayed using the document.write() method.
Output
After executing the code, the display represents the output in milliseconds using the getTime() method in JavaScript.
Example 2: To Get the Time From User Defined getTime() Method
In this example, the date is taken from the user and then the getTime() method will be applied to it. Let’s see how it works:
Code
<script> // An example for using the getTime() method // While creating Date object
const input = prompt(«What’s your Birthday Date?»); alert(`Your Birthday Date is ${input}`); var date1 = new Date(input); // The information for milliseconds is // extracted using getTime() var date2 = date1.getTime(); // Display timein milliseconds. document.write(date2); </script>
The description of the above code is enlisted here:
Firstly, store the date of birth in a variable named input.
After that, an alert box is generated for that prompt.
Extract the information every millisecond using the getTime() method.
Finally, display the information using the date2 variable.
Output
Upon executing the code, the following interface is observed:
After the execution of the code, the user must input the date of birth, as we entered March 10, 1994. Click on OK to proceed further:
A prompt message is generated for confirmation of the data provided through the user input:
In the end, the milliseconds that have passed since January 1st, 1970, are displayed.
Conclusion
JavaScript is useful for extracting information in milliseconds using the Date.getTime() method. The date object is used to call this method, and it retrieves the values in milliseconds that have passed since January 1st, 1970. This method’s output can be obtained on various modern browsers such as Firefox, Safari, Edge, and Opera. You have learned the working of the getTime() method in JavaScript.
The LINQ Except() method in C#, it returns all the elements in the first dataset that are not present in the second data set. The data set can be an Array, List, ArrayList, SortedList, and etc.
Syntax:
input_source1.Except(input_source2);
Where input_source1 is the first data source and input_source2 is the second data source.
Example 1:
Here, we will create two Arrays that have string elements and apply the Except() method to return only elements from the first Array that are not present in the second Array.
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Linuxhint { staticvoid Main() { //create array of strings with 5 strings string[] first_strings ={«Linuxhint»,«java»,«python»,«backbone.js»,«ember.js»}; //create array of strings with 3 strings string[] second_strings ={«Linuxhint»,«java»,«html»};
Console.WriteLine(«——–First Array——–«); foreach (var values1 in first_strings) { Console.WriteLine(values1); } Console.WriteLine(«——–Second Array——–«); foreach (var values1 in second_strings) { Console.WriteLine(values1); }
//apply Except() var final=first_strings.Except(second_strings);
1. So first, we created two String Arrays named first_strings,second_strings.
2. After that, we are displaying the flagrante values present in the two arrays using a foreach loop.
3. Use the Except() method and display the values using the foreach loop.
Example 2:
Here, we will create two Arrays that have integer elements and apply the Except() method to return only values from the first Array that are not present in the second Array.
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Linuxhint { staticvoid Main() { //create array of integers int[] first_integers ={20,34,56,23,67,100}; //create array of integers int[] second_integers ={20,23,34,56,67};
Console.WriteLine(«——–First Array——–«); foreach (var values1 in first_integers) { Console.WriteLine(values1); } Console.WriteLine(«——–Second Array——–«); foreach (var values1 in second_integers) { Console.WriteLine(values1); }
//apply Except() var final=first_integers.Except(second_integers);
1. So first, we created two Integer Arrays named first_integers and second_integers.
2. After that, we are displaying the flagrante values present in the two arrays using a foreach loop.
3. Use the Except() method and display the values using the foreach loop.
Conclusion
The LINQ Except() method in C# returns all the elements in the first dataset that are not present in the second data set. Here, we used Array as a data source. Make sure you have to include using System, using System.Linq, using System.Collections, and using System.Collections.Generic.
In this article, we will discuss how to return the last element or default element using the LINQ LastOrDefault() function.
Language Integrated Query language (LINQ) is used to perform operations on the C# collections or Regular data structures.
LINQ LastOrDefault()
LastOrDefault() in LINQ returns the last element from the specified data structure. If there are no elements in the data structure, it will return a default value – 0.
There are two ways to use this method. Let’s look into it.
Approach 1: Using Method
We will use the ordinario LastOrDefault() method to return the last/default element.
Syntax:
Where list is the List object created.
Approach 2: Using Query
We will use the Query similar to SQL expression that returns the last/default element.
Syntax:
from i in list select i.LastOrDefault()
Where list is the List object created.
Example 1:
Here, we will create a list that holds integer elements and we will use LastOrDefault() to return only the last value.
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint {
static public void Main(){
//create list of integers Listfirst_list = new List(){100,200,300,456};
Console.WriteLine(«List: «); foreach (var values in first_list) { Console.WriteLine(values); }
//get the last element from the list var result = first_list.LastOrDefault();
Console.WriteLine(«Last element in the List: «+result);
} }
Output:
Explanation:
1. So first, we created a list data structure with 4 integers.
2. After that, we applied LastOrDefault() to get the last element and display the result.
Example 2:
Here, we will create a list that holds no elements and we will use LastOrDefault() to return the default value.
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint {
static public void Main(){
//create list Listfirst_list = new List();
//get the default element from the list var result = first_list.LastOrDefault();
Console.WriteLine(«Default element in the List: «+result);
} }
Output:
Explanation:
1. So first, we created a list data structure with no values.
2. After that, we applied LastOrDefault() to get the default element and display it using the Console.Write() function.
Example 3:
Here, we will create two lists that hold integer and string elements separately. Get the last element from both the lists using Query.
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint {
static public void Main(){
//create list of integers Listfirst_list = new List(){100,200,300,456};
//create list of strings Listsecond_list = new List(){«linuxhint»,«sravan»,«vignan»,«java»};
//get the last element from the list var result2 =(from i in second_list select i).LastOrDefault();
Console.WriteLine(«Last element in the List: «+result2);
} }
Output:
Explanation:
1. Let’s create two Lists:
2. Now, return Last element from both the lists:
Conclusion
LastOrDefault() in LINQ returns only the last element or default element from the data structure. Here, we used List as a data structure. If the data structure has no elements, a default value 0 is returned. We implemented the LINQ LastOrDefault() method in two ways. Make sure that use has to include – using System.Linq and using System.Collections.Generic command lines in your code.
Suppose In a Datasource there are elements with different data types like string,Integer, double etc., and you need to get only a particular type, you should know about OfType() method available in C#. The data source can be an ArrayList.
OfType()
OfType() method in LINQ is used to eliminate the unnecessary data type elements and return only elements of a single data type.
Syntax:
input_source.OfType<datatype>()
Where:
input_source can be an Arraylist.
datatype is the type we will return like string,int,double etc.
Example 1:
Here, we will create a data source named Array List and it has three data type elements. So, we will extract the elements only of string type.
The syntax should be:
input_source.OfType();
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Linuxhint {
public staticvoid Main() { //create an array list that has multiple datatype elements. var my_arraylist=new ArrayList(){1,«Linuxhint»,«java»,4.56,90.5355,6};
//display the ArrayList foreach (var result in my_arraylist){ Console.WriteLine(result); } Console.WriteLine(«————————«);
//return only string type elements var string_types=my_arraylist.OfType();
//display foreach (var result in string_types){ Console.WriteLine(result); } } }
Output:
Explanation:
Create an array list named – my_arraylist.
Return only strings.
Display the result using a foreach loop.
Example 2:
Here, we will create a data source named Array List and it has three data type elements. We will extract the elements only of integer type.
The syntax should be:
input_source.OfType();
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Linuxhint {
public staticvoid Main() { //create an array list that has multiple datatype elements. var my_arraylist=new ArrayList(){1,«Linuxhint»,«java»,4.56,90.5355,6};
//display the ArrayList foreach (var result in my_arraylist){ Console.WriteLine(result); } Console.WriteLine(«————————«);
//return only integer type elements var int_types=my_arraylist.OfType();
//display foreach (var result in int_types){ Console.WriteLine(result); } } }
Output:
Explanation:
Create an array list named – my_arraylist.
Return only integers.
Display the result using a foreach loop.
Example 3:
Here, we will create a data source named Array List and it has three data type elements. We will extract the elements only of double type.
The syntax should be:
input_source.OfType();
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Linuxhint {
public staticvoid Main() { //create an array list that has multiple datatype elements. var my_arraylist=new ArrayList(){1,«Linuxhint»,«java»,4.56,90.5355,6};
//display the ArrayList foreach (var result in my_arraylist){ Console.WriteLine(result); } Console.WriteLine(«————————«);
//return only double type elements var double_types=my_arraylist.OfType();
//display foreach (var result in double_types){ Console.WriteLine(result); } } }
Output:
Explanation:
Create an array list named – my_arraylist.
Return only double type values.
Display the result using a foreach loop.
Conclusion
In this tutorial, we discussed the OfType() method. OfType() method in LINQ is used to eliminate the unnecessary data type elements and return only elements of a single data type. In projects, if you need only particular data types like strings, integers or double values, you can specify int to return only integer values, string to return string values and double to return double values.
In this article, we will discuss how to order the data in descending order using the OrderByDescending() method through LINQ.
Language Integrated Query language (LINQ) is used to perform operations on the C# collections or Regular data structures. It is used to perform queries similar to SQL like expressions.
LINQ OrderByDescending()
OrderByDescending() in LINQ is used to return all elements in a descending order within a given data structure.
OrderByDescending() is also applied on the data that has multiple values in each row. It is possible to order the data based on a particular value in each row.
Syntax:
If the values are single:
list.OrderByDescending(element => element)
element iterates the values in a list and arrange them in Descending order.
element iterates the values in a list and arranges them in descending order and the variable is the value in which the values are arranged in Descending order based on this variable.
Let’s explore this method.
Example 1:
Here, we will create a list that holds integer elements and we will use OrderByDescending() to return these elements in an order.
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint {
static public void Main(){
//create data Listfirst_list = new List(){120,80,45,123,456,45,120,8,9,0};
Console.WriteLine(«List: «); foreach (var values in first_list) { Console.WriteLine(values); }
//order the elements in descending order var ordered_data = first_list.OrderByDescending(element => element);
Console.WriteLine(«Ordered data: «);
//return one by one value from the ordered_data foreach (var result in ordered_data) { Console.WriteLine(result); }
} }
Output:
Explanation:
1. We created a list data structure with 10 integers.
2. After that, we applied OrderByDescending() to order that list by iterating the list using iterator-element.
3. Finally, we can display the result by iterating the ordered_data using a foreach loop.
Example 2:
Here, we will create a list that holds string elements and we will use OrderByDescending() to return these elements in descending order.
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint {
static public void Main(){
//create data Listfirst_list = new List(){«Linuxhint»,«sravan»,«kumar»,«A»};
Console.WriteLine(«List: «); foreach (var values in first_list) { Console.WriteLine(values); }
//order the elements in descending order var ordered_data = first_list.OrderByDescending(element => element);
Console.WriteLine(«Ordered data: «);
//return one by one value from the ordered_data foreach (var result in ordered_data) { Console.WriteLine(result); }
} }
Output:
Explanation:
1. First, we created a list data structure with 4 strings.
2. After that, we applied OrderBy() to order that list by iterating the list using iterator-element.
3. Finally, we can display the result by iterating the ordered_data using a foreach loop.
Example 3:
Let’s create Food that holds three attributes – food_price, name, and quantity.
Order the values based on food_price.
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint { //define the data for Food class Food { public int food_price { get; set;} public string name { get; set;} public int quantity { get; set;} } static public void Main(){
foreach (var value in first_list) { Console.WriteLine(value.food_price+«->»+value.name+«->»+value.quantity); }
Console.WriteLine(«————————–Ordered data (Descending)————————–«);
//order the data based on food_price values in Descending order var ordered_data = first_list.OrderByDescending(element =>element.food_price); foreach (var result in ordered_data) { Console.WriteLine(result.food_price+«->»+result.name+«->»+result.quantity); }
} }
Output:
Explanation:
1. First, we have to declare the structure:
We defined three attributes with food_price and quantity as integer type and name as string type.
2. Next, we created a list named first_list from the structure-Food.
3. Add the values to the above created list.
We have added 5 values.
4. Apply OrderBy() to order the values based on food_price column.
5. Display the result with a foreach loop.
The entire list is ordered in descending order based on values in food_price.
Conclusion
In this C# – LINQ tutorial, we saw how to order the data in descending order with the OrderByDescending() function. It will return all elements in descending order within a given data structure. It is also possible to order the data based on a particular value in each row. We discussed three different examples to understand the concept better.
In this article, we will discuss how to order the data based on multiple attributes in descending order using the ThenBy() Method() method through LINQ.
Language Integrated Query language (LINQ) is used to perform operations on the C# collections or Ordinario data structures. It is used to perform queries similar to SQL Like expressions.
LINQ ThenBy() Method
ThenBy() Method in LINQ is used to return all elements in an ascending order within a given data structure based on multiple attributes. So we have to use the ThenBy() Method along with the OrderBy()/OrderByDescending() methods.
First we will apply the OrderBy()/OrderByDescending() method and ThenBy() is used.
Syntax:
If the values are single:
ThenBy(element => element)
The element iterates the values in a list and arranges them in ascending order.
If there are multiple values:
ThenBy(element => element.variable)
The element iterates the values in a list and arranges them in ascending order, and the variable is the value by which the values are arranged in ascending order based on this variable.
Whereas, a list is the input list that holds values and a variable refers to an attribute name in which we will order based on this variable only.
Example 1: OrderBy() with ThenBy()
Let’s create Food that holds three attributes – food_price, name, and quantity.
Order the values based on food_price with OrderBy() and food_name with ThenBy().
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint { //define the data for Food class Food { public int food_price { get; set;} public string name { get; set;} public int quantity { get; set;} } static public void Main(){
//create data List first_list = new List(); //add values first_list.Add(new Food { food_price=300,name=«parota»,quantity=1}); first_list.Add(new Food { food_price=800,name=«paneer»,quantity=4}); first_list.Add(new Food { food_price=100,name=«mushroom»,quantity=2}); first_list.Add(new Food { food_price=100,name=«chips»,quantity=10}); first_list.Add(new Food { food_price=400,name=«fruits»,quantity=8});
foreach (var value in first_list) { Console.WriteLine(value.food_price+«->»+value.name+«->»+value.quantity); }
//order the data based on food_price values in ascending and name in ascending var ordered_data = first_list.OrderBy(element => element.food_price).ThenBy(element => element.name); foreach (var result in ordered_data) { Console.WriteLine(result.food_price+«->»+result.name+«->»+result.quantity); }
} }
Output:
Explanation:
1. First we have to declare the structure:
We defined three attributes with food_price and quantity as an integer type and name as a string type.
2. Next we created a list named first_list from the structure-Food.
3. Add the values to the above-created list.
We have added 5 values.
4. Apply OrderBy() to order the values based on the food_price column in ascending order and ThenBy) method to order the values in the name column in ascending order.
5. Display the result with a foreach loop.
So the entire list is ordered in ascending order based on values in food_price and in ascending order based on values in the name attribute.
Example 2: OrderByDescending() with ThenBy()
Let’s create Food that holds three attributes: food_price, name, and quantity.
Order the values based on food_price with OrderByDescending() and food_name with ThenBy().
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint { //define the data for Food class Food { public int food_price { get; set;} public string name { get; set;} public int quantity { get; set;} } static public void Main(){
//create data List first_list = new List(); //add values first_list.Add(new Food { food_price=300,name=«parota»,quantity=1}); first_list.Add(new Food { food_price=800,name=«paneer»,quantity=4}); first_list.Add(new Food { food_price=100,name=«mushroom»,quantity=2}); first_list.Add(new Food { food_price=100,name=«chips»,quantity=10}); first_list.Add(new Food { food_price=400,name=«fruits»,quantity=8});
foreach (var value in first_list) { Console.WriteLine(value.food_price+«->»+value.name+«->»+value.quantity); }
//order the data based on food_price values in descending and name in ascending order. var ordered_data = first_list.OrderByDescending(element => element.food_price).ThenBy(element => element.name); foreach (var result in ordered_data) { Console.WriteLine(result.food_price+«->»+result.name+«->»+result.quantity); }
} }
Output:
Explanation:
1. First we have to declare the structure:
So, we defined three attributes, with food_price and quantity as an integer type and name as a string type.
2. Next we created a list named first_list from the structure-Food.
3. Add the values to the above created list.
We have added 5 values.
4. Apply OrderByDescending() to order the values based on the food_price column in descending order and ThenBy() method to order the values in the name column in ascending order.
5. Display the result with a foreach loop.
So the entire list is ordered in descending order based on values in food_price and in ascending order based on values in the name attribute.
Example 3: OrderBy() with multiple ThenBy()
Let’s create Food that holds three attributes: food_price, name, and quantity.
Order the values based on food_price with OrderByDescending() and food_name,quantity with ThenBy().
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint { //define the data for Food class Food { public int food_price { get; set;} public string name { get; set;} public int quantity { get; set;} } static public void Main(){
//create data List first_list = new List(); //add values first_list.Add(new Food { food_price=300,name=«parota»,quantity=1}); first_list.Add(new Food { food_price=800,name=«paneer»,quantity=4}); first_list.Add(new Food { food_price=100,name=«mushroom»,quantity=2}); first_list.Add(new Food { food_price=100,name=«chips»,quantity=10}); first_list.Add(new Food { food_price=400,name=«fruits»,quantity=8});
foreach (var value in first_list) { Console.WriteLine(value.food_price+«->»+value.name+«->»+value.quantity); }
//order the data based on food_price values in descending and name,quantity in ascending order. var ordered_data = first_list.OrderByDescending(element => element.food_price). ThenBy(element => element.name). ThenBy(element => element.quantity); foreach (var result in ordered_data) { Console.WriteLine(result.food_price+«->»+result.name+«->»+result.quantity); }
} }
Output:
Explanation:
1. First we have to declare the structure:
So, we defined three attributes with food_price and quantity as an integer type and name as a string type.
2. Next we created a list named first_list from the structure-Food.
3. Add the values to the above-created list.
We have added 5 values.
4. Apply OrderByDescending() to order the values based on the food_price column in descending order and the ThenBy() method to order the values in the name and quantity columns in ascending order.
5. Display the result with a foreach loop.
So, the entire list is ordered in descending order based on values in food_price and in ascending order based on values in name and quantity attributes.
Conclusion
In the LINQ tutorial, we saw how to order the data by multiple attributes with the ThenBy() method and OrderBy()/OrderByDescending() functions. It is also possible to order the data based on a particular value by providing multiple attributes. We discussed three different examples to understand the concept better. Make sure that you import the using System, System.Linq, and System.Collections.Generic;
In this article, we will discuss how to order the data based on multiple attributes in descending order using the ThenByDescending() Method() method through LINQ.
Language Integrated Query language (LINQ) is used to perform operations on the C# collections or Habitual data structures. It is used to perform queries similar to SQL-Like expressions.
LINQ ThenByDescending() Method
ThenByDescending() Method in LINQ is used to return all elements in descending order within a given data structure based on multiple attributes. So we have to use the ThenByDescending() Method along with the OrderBy() method.
First we will apply the OrderBy()/OrderByDescending() method and it is followed by ThenByDescending().
Syntax:
If the values are single:
ThenByDescending(element => element)
The element iterates the values in a list and arranges them in descending order.
If there are multiple values:
ThenByDescending(element => element.variable)
The element iterates the values in a list and arranges them in descending order and the variable is the value in which the values are arranged in descending order based on this variable.
Whereas, a list is the input list that holds values and a variable refers to an attribute name in which we will order based on this variable only.
Example 1: OrderBy() with ThenByDescending()
Let’s create Food that holds three attributes – food_price, name, and quantity.
Order the values based on food_price with OrderBy() and food_name with ThenByDescending().
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint { //define the data for Food class Food { public int food_price { get; set;} public string name { get; set;} public int quantity { get; set;} } static public void Main(){
//order the data based on food_price values in ascending and name in descending var ordered_data = first_list.OrderBy(element =>element.food_price).ThenByDescending(element => element.name); foreach (var result in ordered_data) { Console.WriteLine(result.food_price+«->»+result.name+«->»+result.quantity); }
} }
Output:
Explanation:
1. First we have to declare the structure:
So, we defined three attributes with food_price and quantity as an integer type and name as a string type.
2. Next we created a list named first_list from the structure-Food.
3. Add the values to the above-created list.
We have added 5 values.
4. Apply OrderBy() to order the values based on the food_price column in ascending order and ThenByDescending() method to order the values in the name column in descending order.
5. Display the result with a foreach loop.
So the entire list is ordered in ascending order based on values in food_price and in descending order based on values in the name attribute.
Example 2: OrderByDescending() with ThenByDescending()
Let’s create Food that holds three attributes: food_price, name, and quantity.
Order the values based on food_price with OrderByDescending() and food_name with ThenByDescending().
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint { //define the data for Food class Food { public int food_price { get; set;} public string name { get; set;} public int quantity { get; set;} } static public void Main(){
//order the data based on food_price values in descending and name in descending order. var ordered_data = first_list.OrderByDescending(element =>element.food_price).ThenByDescending(element => element.name); foreach (var result in ordered_data) { Console.WriteLine(result.food_price+«->»+result.name+«->»+result.quantity); }
} }
Output:
Explanation:
1. First we have to declare the structure:
So we defined three attributes, with food_price and quantity as an integer type and name as a string type.
2. Next, we created a list named first_list from the structure-Food.
3. Add the values to the above-created list.
We have added 5 values.
4. Apply OrderByDescending() to order the values based on the food_price column in descending order and ThenByDescending() method to order the values in the name column in descending order.
5. Display the result with a foreach loop.
So the entire list is ordered in descending order based on values in food_price and in descending order based on values in the name attribute.
Example 3: OrderBy() with multiple ThenByDescending()
Let’s create Food that holds three attributes: food_price, name, and quantity.
Order the values based on food_price with OrderByDescending() and food_name,quantity with ThenByDescending().
using System;
using System.Linq;
using System.Collections.Generic;
//create a class – Linuxhint class Linuxhint { //define the data for Food class Food { public int food_price { get; set;} public string name { get; set;} public int quantity { get; set;} } static public void Main(){
//order the data based on food_price values in descending and name,quantity in descending order. var ordered_data = first_list.OrderByDescending(element =>element.food_price). ThenByDescending(element => element.name). ThenByDescending(element =>element.quantity); foreach (var result in ordered_data) { Console.WriteLine(result.food_price+«->»+result.name+«->»+result.quantity); }
} }
Output:
Explanation:
1. First we have to declare the structure:
So we defined three attributes with food_price and quantity as an integer type and name as string type.
2. Next we created a list named first_list from the structure-Food.
3. Add the values to the above-created list.
We have added 5 values.
4. Apply OrderByDescending() to order the values based on the food_price column in descending order and ThenByDescending() method to order the values in the name and quantity columns in descending order.
5. Display the result with a foreach loop.
So the entire list is ordered in descending order based on values in food_price and in descending order based on values in name and quantity attributes.
Conclusion
In the LINQ tutorial, we saw how to order the data by multiple attributes with the ThenByDescending() method, along with the OrderBy()/OrderByDescending() functions. It is also possible to order the data based on a particular value by providing multiple attributes. We discussed three different examples to understand the concept better. Make sure that you import the using System, System.Linq and System.Collections.Generic;
We may request cookies to be set on your device. We use cookies to let us know when you visit our websites, how you interact with us, to enrich your user experience, and to customize your relationship with our website.
Click on the different category headings to find out more. You can also change some of your preferences. Note that blocking some types of cookies may impact your experience on our websites and the services we are able to offer.
Essential Website Cookies
These cookies are strictly necessary to provide you with services available through our website and to use some of its features.
Because these cookies are strictly necessary to deliver the website, refusing them will have impact how our site functions. You always can block or delete cookies by changing your browser settings and force blocking all cookies on this website. But this will always prompt you to accept/refuse cookies when revisiting our site.
We fully respect if you want to refuse cookies but to avoid asking you again and again kindly allow us to store a cookie for that. You are free to opt out any time or opt in for other cookies to get a better experience. If you refuse cookies we will remove all set cookies in our domain.
We provide you with a list of stored cookies on your computer in our domain so you can check what we stored. Due to security reasons we are not able to show or modify cookies from other domains. You can check these in your browser security settings.
Google Analytics Cookies
These cookies collect information that is used either in aggregate form to help us understand how our website is being used or how effective our marketing campaigns are, or to help us customize our website and application for you in order to enhance your experience.
If you do not want that we track your visit to our site you can disable tracking in your browser here:
Other external services
We also use different external services like Google Webfonts, Google Maps, and external Video providers. Since these providers may collect personal data like your IP address we allow you to block them here. Please be aware that this might heavily reduce the functionality and appearance of our site. Changes will take effect once you reload the page.
Google Webfont Settings:
Google Map Settings:
Google reCaptcha Settings:
Vimeo and Youtube video embeds:
Other cookies
The following cookies are also needed - You can choose if you want to allow them:
Privacy Policy
You can read about our cookies and privacy settings in detail on our Privacy Policy Page.