Trending November 2023 # How Charts Works Inwith Examples? # Suggested December 2023 # Top 20 Popular

You are reading the article How Charts Works Inwith Examples? updated in November 2023 on the website Tai-facebook.edu.vn. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 How Charts Works Inwith Examples?

Introduction to chúng tôi charts

Charts are used to show the data in the forms of visual which makes them look attractive. We have different types of charts available in chúng tôi which can be used to show data in visual format. We have different type of chart in Vue like pie, line, bar and many more we can also modify this chart according to requirement. This increases the visibility of the data to user and make statistics easier to understand.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

mounted () { this.renderChart(data, options) }

In order to use this we need to import the Chart by the name form Vue-charts library, now we will just see how we can define the chart into our program to make the data visualize.

How do charts work in Vue.js?

As now we know that charts makes our data to look more user friendly and make it easier to understand. It helps to protect our data and all the calculation or we can say an approx. value for the variable in more convenient way. We can use this charts on our dashboard of our application where all the data and statistics of the application are shown. By using this charts we can show day to-day, moth to month as well as year to year data in more under stable form. We can also change the color of the charts, font and make them more interactive by using the various function available in chúng tôi chart library.

In order to use the chart library into chúng tôi program we need to install some files before using them.

Let’s see the steps which need to be taken in order to use this:

1. Here we are using vue-chart js library we also have so many other options available but for now we are using this. So first step is to install this library we can do this by using npm or yarn.

Open your command prompt and run the below command using npm option, this will install the dependence of vue-chartjs and chúng tôi as well.

npm install vue-chartjs chart.js

2. After this we can import this library into our js file and use their charts available and modify them. In order to import them we need to write one import statement into our file.

Example:

import { your_class_name } from 'vue-chartjs'

3. Before this we will include some files into our application these are the .js files which is required to import before even start.

chart.min.js

vue-chartjs.min.js

This files can be import by using the script tag and mentioned their path as well by using the src attribute.

Example:

4. All the different chart available inside the chúng tôi and to make them feasible we have vue-chartjs to use them. We can mention the name of the chart and import them in our js file.

Examples of chúng tôi charts

Given below are the examples of chúng tôi charts:

Example #1

In this example we are creating line chart using the chart,js with chúng tôi and trying to show the data of student. Using different function here and also creating the dataset t mount our data on chart.

HTML File Code:

Js File Code:

extends: VueChartJs.Line, mounted () { this.renderChart({ labels: [‘Amit’, ‘Suimt’, ‘AmBita’, ‘Vinta’, ‘Aman’, ‘Ankit’, ‘Itisha’, ‘Latika’], datasets: [ { label: ‘Set one’, backgroundColor: ‘#f87979’, data: [5, 8, 2, 15, 30, 15, 30 , 20] }, { label: ‘Set two’, backgroundColor: ‘#ccffcc’, data: [10, 5, 20, 15, 30, 25, 40 , 35] } ] }, {responsive: true, maintainAspectRatio: false}) } }) var vm = new Vue({ el: ‘.demoapp’, data: { message: ‘Line chart in Vue Js’ } })

Output:

Example #2

In this example, we are creating a bar graph using chúng tôi with chúng tôi and trying to show the student data.

HTML File Code:

extends: VueChartJs.Bar, mounted () { this.renderChart({ labels: [‘Amit’, ‘Suimt’, ‘AmBita’, ‘Vinta’, ‘Aman’, ‘Ankit’, ‘Itisha’, ‘Latika’], datasets: [ { label: ‘Set one’, backgroundColor: ‘#f87979’, data: [5, 8, 2, 15, 30, 15, 30 , 20] }, { label: ‘Set two’, backgroundColor: ‘#ccffcc’, data: [10, 5, 20, 15, 30, 25, 40 , 35] }, { label: ‘Set three’, backgroundColor: ‘#ffb3d1’, data: [10, 5, 20, 15, 30, 25, 40 , 35] } ] }, {responsive: true, maintainAspectRatio: false}) } }) var vm = new Vue({ el: ‘.demoapp’, data: { message: ‘Bar chart in Vue Js Demo’ } })

Output:

Example #3

In this example we are trying to create pie chart by using the chúng tôi with chúng tôi to show the data of student here. Also we have used to dataset object to mount our data into the chart using different colors.

HTML File Code:

Js File Code:

extends: VueChartJs.Pie, mounted () { this.renderChart({ labels: [‘Amit’, ‘Suimt’, ‘AmBita’, ‘Vinta’, ‘Aman’, ‘Ankit’, ‘Itisha’, ‘Latika’], datasets: [ { label: ‘Set one’, backgroundColor: ‘#f87979’, data: [5, 8, 2, 15, 30, 15, 30 , 20] }, { label: ‘Set two’, backgroundColor: ‘#ccffcc’, data: [10, 5, 20, 15, 30, 25, 40 , 35] }, { label: ‘Set three’, backgroundColor: ‘#ffb3d1’, data: [10, 5, 20, 15, 30, 25, 40 , 35] } ] }, {responsive: true, maintainAspectRatio: false}) } }) var vm = new Vue({ el: ‘.demoapp’, data: { message: ‘Pie chart in Vue Js Demo’ } })

Output:

Conclusion

The chart are used to provide the effective representation of data to the user so that they can easily understand the statistics of data. Moreover this charts are used on the dashboard of application to look it more interactive. They help us to visualize the data easily.

Recommended Articles

This is a guide to chúng tôi charts. Here we discuss the introduction, syntax, and working of charts in chúng tôi along with examples and code implementation. You may also have a look at the following articles to learn more –

You're reading How Charts Works Inwith Examples?

How Distinct Command Works With Examples

Introduction to MongoDB Distinct

MongoDB distinct is used to find distinct values from a single collection and retrieved results of the query in an array, MongoDB distinct is used to retrieve distinct values from the collection. Distinct in MongoDB is very important and useful to retrieve distinct data from a single collection. Distinct is different from MongoDB find the method, distinct will returns the array of all the distinct values from the collection. This will return only distinct data from the collection, if in one collection thousands of documents and we need only those documents which were distinct each other same time we have used distinct in MongoDB.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax

Below is the syntax of distinct in MongoDB.

collection_name.distinct (field, query)

collection_name.distinct (field, query, options)

Parameter

Collection name: Collection name is defined as retrieved documents from the collection by using a distinct method. We can retrieve distinct values from the collection by using distinct methods.

Distinct: This will return only distinct data from the collection. This is very important and useful to retrieve distinct data from a single collection. This is used to retrieve distinct values from the collection.

Field: Field has specified that return distinct value from the field we have specified with distinct methods. The field is an essential and useful parameter in a distinct method.

Options: This is an optional parameter in MongoDB distinct command. This is an additional option used in the distinct command. It is available only if the document specifies the options.

Query: Query distinct method defines the document from which we have to retrieve the collection’s distinct value. The query is a handy and important parameter in a distinct method.

How Distinct Command works in MongoDB?

Below is the working of distinct command:

The distinct method in MongoDB uses an index on the field while doing a distinct operation on collection.

This will return only distinct data from the collection, if in one collection thousands of documents and we need only those documents which were distinct each other same time we have used distinct in MongoDB.

When we have used or specifies collation in a distinct method, we need to specify a mandatory locale to define the field with collation in a distinct method.

If the field’s values were an array, then distinct methods consider each element of the field as a separate value.

If suppose array contains a value as [1, 2, 1, [1], 2], then distinct methods consider it as [1, 2, [1]] as a result.

Below example states will consider the array field as each element as separate values.

Code #1

use stud_array

Output:

Code #2

db.stud_array.insert({"stud_id" : 1, "semester" : 5, "grades" : [ 90, 90, [92], 92 ] })

Output:

Code #3

db.stud_array.distinct("grades")

Output:

Examples to Implement MongoDB Distinct

Below is the example of a distinct method in MongoDB.

We have taken an example of student_datatable to describe an example of a distinct method is as follows. Below is the data description of the student_data table are as follows.

Example #1

use student_data

Example #2

db.student_data.find()

1. Return distinct values from field

The below example shows that return distinct value from the field. We have used the semester field from the student_data table to describe distinct values from the field.

Code:

db.student_data.distinct ("semester")

 Output:

Explanation: In the above example, we have retrieved distinct values from the semester field. The result of values from the customer field is 3, 4, and 5.

2. Return distinct values from field

The below example shows that return distinct value from the array field. We have used the grade array field from the student_data table to describe distinct values from the array field.

Code:

db.student_data.distinct ("grades")

Explanation: In the above example, we have retrieved distinct values from the grades field. The above example states that distinct methods in MongoDB consider the array field as each element of the field as a separate value. In the above example output of 92 and 95 occur double because distinct considered it a separate element.

3. Query with a distinct method

The below example shows that query with the distinct value from the field. We have used semester and grades field from the student_data table to describe queries with distinct fields.

Code:

db.student_data.distinct ("semester",{ grades: 90 })

Output:

4. Using collation with a distinct method

The below example shows that collation with the distinct method in MongoDB. We have used the semester field from the student_data table to describe collation with the method.

Code:

db.student_data.distinct( "semester", {}, { collation: { locale: "fr", strength: 1 } } )

Output:

Recommended Articles

This is a guide to MongoDB Distinct. Here we discuss syntax, parameter, the working of distinct command with examples to implement. You can also go through our other related articles to learn more –

How Include Works In Linq With Examples?

Introduction to LINQ Include

Web development, programming languages, Software testing & others

Syntax:

Let’s understand the following syntax,

var C_OrderDetails=context.customer details.Include ("OrderDetails").ToList();

In this syntax, we use the include method to combine the related entities in the same query, like merging multiple entities in a single query.

How does include work in LINQ? Var COrderDetails=context.CustomerDetails.Include ("OrderDetails").ToList();

By using only SQL statements instead of using the Include() methods, we need to generate the following queries to retrieve the same above,

SELECT * FROM CustomerDetails;

Instead of using Include (“OrderDetails”), the code looks as follows,

SELECT * FROM CustomerDetails JOIN OrderDetails ON Customer_ID=OrderDetails.Customer_ID; Var Customer_OrderDetails= context.CustomerDetails.Include("OrderDetails").Include("LineItems").Include ("ProducDetails").ToList();

We can make it use multiple calls to Include() to get the objects along various paths. If you require the objects in the same path, you must make a single call specifying the entire path.

Example

When using Include, if we have n number of queries to execute n number of times that is time-consuming, then it’s like select N+1 problem; this issue happens only because the lazy loading mechanism enables by default to execute a single query n number of queries to do something. So it’s better to avoid the select N+1 problem in Entity Framework; we need to use the Include Method, which helps to build a single query with required data using the Join clause, and this is the most resourceful way compared to executing queries multiple times.

Let’s see the sample program with the use of LINQ_Include. We need to include the namespace chúng tôi entity which the LINQ Include is an extension method of the Data.Entity namespace. Entity Framework version provides LINQ Include() by using chúng tôi and System.Data.Entity.

Code:

using System; using System.Data.Entity; using System.Linq; using System.Collections.Generic; public class Program_LINQ_Include { public static void Main() { Inserting_Data(); using (var context = new EntityContext()) { var customers = context.Customers .ToList(); Displaying_Data(customers); } } public static void Inserting_Data() { using (var context = new EntityContext()) { context.BulkInsert(CustomerData()); context.BulkInsert(InvoiceData()); context.BulkInsert(ItemData()); } } { { new Customer() { Name ="Peter"}, new Customer() { Name ="Smith"}, new Customer() { Name ="James"} }; return list; } { { new Invoice() { Date = new DateTime(2023,5,3), CustomerID = 1}, new Invoice() { Date = DateTime.Now.AddDays(-5), CustomerID = 1}, new Invoice() { Date = DateTime.Now.AddDays(-3), CustomerID = 1}, new Invoice() { Date = new DateTime(2023,4,15), CustomerID = 2}, new Invoice() { Date = new DateTime(2023,2,20), CustomerID = 3}, new Invoice() { Date = new DateTime(2023,5,22), CustomerID = 3}, }; return list; } { { new Item() { Name = "Mobile-Charger", InvoiceID = 1}, new Item() { Name = "Laptop-DELL", InvoiceID = 1}, new Item() { Name = "Stationeries", InvoiceID = 1}, new Item() { Name = "Note-Books", InvoiceID = 2}, new Item() { Name = "DataCard", InvoiceID = 2}, new Item() { Name = "PenDrive", InvoiceID = 3}, new Item() { Name = "Water-Bottles", InvoiceID = 3}, new Item() { Name = "Stationeries", InvoiceID = 3}, new Item() { Name = "DataCard", InvoiceID = 4}, new Item() { Name = "School-Bags", InvoiceID = 4}, new Item() { Name = "Table-Chairs", InvoiceID = 4}, new Item() { Name = "Lap-Table", InvoiceID = 4}, new Item() { Name = "Mobile-Charger", InvoiceID = 5}, new Item() { Name = "School-Bags", InvoiceID = 5}, new Item() { Name = "Stationeries", InvoiceID = 6}, new Item() { Name = "Laptop-DELL", InvoiceID = 6}, new Item() { Name = "Loptop-Cover", InvoiceID = 6}, new Item() { Name = "PenDrive", InvoiceID = 6}, new Item() { Name = "Memory-Card", InvoiceID = 6}, new Item() { Name = "Mobile-Charger", InvoiceID = 6}, new Item() { Name = "School-Bags", InvoiceID = 6}, new Item() { Name = "Touch-Pad", InvoiceID = 6}, }; return list; } { foreach(var customer in list) { Console.WriteLine(customer.Name); foreach(var invoice in customer.Invoices) { Console.WriteLine("t" + invoice.Date); foreach(var item in invoice.Items) { Console.WriteLine("tt" + item.Name); } } } Console.WriteLine("tt"); } }

Output:

Let’s understand the above example, like how the LINQ Includes functionality to load the related entities. To assume that the Customer_Details Object has links to its Invoice_Details and those orders have an ItemData reference. Likewise, we can make several links to the related objects by using LINQ Include(), which allows you to specify the related entities to be read from the database in a single query.

Conclusion

I have explained the LINQ Include() method with several examples programmatically in this article. It enables us to retrieve the related entities from the database in the same query. Using the Include method in a single query, we can easily read all related entities from the database.

Recommended Articles

This is a guide to LINQ Include. Here we discuss the Introduction, Syntax, and working of include method, example, and code implementation. You may also have a look at the following articles to learn more –

How Json Works In Mongodb With Examples

Introduction to MongoDB JSON

MongoDB JSON is the lightweight interchange format; we can easily transfer MongoDB JSON from one system to other. Also, we can easily read and write the file; the abbreviated name of MongoDB JSON is JavaScript object notation. In MongoDB, high-level JSON has two entities. First is an object, and the second is an array; the object is nothing but the value pair collection, and the array is a list of order values; using these two entities, we can develop complete documents in MongoDB. While creating a JSON object is started with braces and then comes key and value.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax of MongoDB JSON

Given below is the syntax mentioned:

1. MongoDB JSON document structure syntax.

}

In the above syntax, field1 to fieldN contains the field which was we have used in the JSON documents.

Value1 to ValueN is the value of the JSON field.

Mongoexport –collection = collection_name –db = db_name –out = filename.JSON

In the above syntax, we are creating the dump file.

The parameter mongoexport is used to export the collection into the JSON file.

Collection parameter is used to export the specified collection into the file.

DB parameter is used to export the specified database collection into the file.

Out parameter is the default that we need to use when exporting any collection in MongoDB.

The filename is the name of the JSON dump file.

3. Import the MongoDB JSON file.

In the above syntax, we are importing the JSON dump file into the specified collection.

The parameter mongoimport is used for import the JSON file data.

The collection parameter is used to import the data into the specified collection from the file.

DB parameter is used to import the data into a specified database collected from the file.

How JSON Works in MongoDB?

It is the plain text which was written in JavaScript object notation. We can use it to send the data between one computer to another computer. The use of JSON in MongoDB is very easy; also, we can use the JavaScript built-in function to convert the JSON strings into the object of JavaScript’s.

There is two built-in functions:

JSON.parse ()

JSON. Stringify ()

It supports all the data types.

Below data type is supported by MongoDB JSON:

Number

Array

Boolean

String

It makes the notation of key-value pair using strings, and it will easily be exported and imported into the various tools. The important function of JSON is to transmit the data between web applications and servers. It is basically used the alternate of an XML, which is the language-independent data format. It has a UTF-8 string format. Thus, humans and machines both understand and read the data of files.

It provides a flexible database and schema design as compared to the tabular data model, which was used in relational database models. Basically, documents are polymorphic; the fields can vary from one document to another within the same collection. Using it, we have no need to create the structure of documents for the database. We can directly start our development without creating any structure.

Examples of MongoDB JSON

Different examples are mentioned below:

Example #1

Insert the data using string data types.

In the below example, we have inserted the string value name as ABC into the MongoDB_JSON collection. Thus, the name attribute shows the field, and the ABC string shows the value of the field.

Code:

db.MongoDB_JSON.find ().pretty ()

Output:

Example #2

Insert the data using numeric data types.

In the below example, we have inserted the numeric value emp_id as 101 into the MongoDB_JSON collection. Thus, the Emp_id attribute shows the field, and 101 integers are shown the value of a field.

Code:

Output:

Example #3

Insert the data using array data types.

In the below example, we have inserted the array value into the MongoDB_JSON collection. Therefore, we have to assign MongoDB_JSON the same name as the field and the value.

Code:

var MongoDB_JSON = ["MongoDB is NoSQL DB", "MySQL is OpenSource DB", "PostgreSQL is object RDBMS"] db.MongoDB_JSON.find ().pretty ()

Output:

Example #4

Insert the data using Boolean data types.

In the below example, we have inserted the Boolean value name as true and the middlename as false into the MongoDB_JSON collection. Name and middlename attribute shows the field, and true, false Boolean value shows the value of the field.

Code:

> db.MongoDB_JSON.find ().pretty ()

Output:

Example #5

Below example shows export MongoDB_JSON collection into the MongoDB_JSON. Json file.

After exporting the data into the JSON file, we can see this file using the cat command. This data comes in a human-readable format.

Code:

[[email protected] ~]# cat MongoDB_JSON. Json

Output:

Example #6

MongoDB import from the JSON file.

The below example shows that import the data into the Mongo_JSON_NEW collection from the MongoDB_JSON. Json file.

Code:

db.Mongo_JSON_NEW.find().pretty()

Output:

Conclusion

They have their multiple data types are available in MongoDB; using this datatype, we can insert the data into the collection. We can import the data into the collection from JSON file using mongoimport; we can also export the collected data into the JSON file using mongoexport.

Recommended Articles

This is a guide to MongoDB JSON. Here we discuss the introduction, how JSON works in MongoDB? and examples for better understanding. You may also have a look at the following articles to learn more –

How Foldleft Function Works In Scala With Examples?

Introduction to Scala foldLeft

Scala foldLeft function can be used with the collection data structure in scala. Also, foldLeft is applicable for both immutable and mutable data structures of collection. This function takes two arguments as parameters. One is the binary operator and the second argument of the collection always points to the current elements of the collection. This binary operator is used to settle the elements of the collection.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax of Scala foldLeft:

This method takes two arguments as a parameter, and it traverses from left to right, so it is named as the foldLeft() method.

def foldLeft[B](z: B)(op: (B, A) ⇒ B): B

Example:

val result = list.foldLeft(1.1)(_ + _)

In this, we give the initial value to the function as 1.1 and try to sum all the elements present in the list. This can be applied to any collection data structure.

How foldLeft Function works in Scala?

foldLeft function traverse the element of collection data structure from left to right to it is named as foldLeft() function in scala. It takes two parameters, and also we can specify the initial value by using this function. This function is a recursive function and helps us from stack-overflow exceptions while programming.

This function is the member function of TraversableOnce in scala. TraversableOnce is a trait built to remove the duplicate code of Traversable and Iterator, which implements the common functions. This trait also contains abstract methods, and the Traversable and Iterator provide this abstract method implementation.

Now we will see one example where we will initialize our list of elements and trying to apply the foldLeft function on it.

Example:

Code:

val myList: Seq[Int] = Seq(10, 30, 50, 60) println(myList)

In this, we are creating one Sequence of integers containing around 4 variables and trying to print out the sequence elements.

Code:

val result = myList.foldLeft(0)(_ + _) println("result is  ::" + result)

After creating the sequence, now we want to sum all the elements present inside the sequence. For this, we are using the foldLeft function. First, we call foldLeft on our collection, followed by the initial value that we have assigned as 0. After that, we use the binary operator + to get the sum of all elements present inside the collection sequence. We can use any binary operator here depend upon the requirement.

We can also use the foldLeft function with string type of collection data structure; we will see one example.

Here we are creating one List if string that contains so many elements into it. After that, we are just printing our newly created list that all.

Example:

Code:

val myList: List[String] = List("amit", "sumit", "vinit", "lalti", "minit") println(myList)

Example:

Now we are trying to add some string after our every element present into the for this, we are using the foldLeft function, and inside this function, we are appending the string that we want to show.

We can also pass a function obtained value directly to the foldLeft function to concatenate the string.

Example:

Code:

val myList: List[String] = List("amit", "sumit", "vinit", "lalti", "minit") println(myList) var result = myList.foldLeft("")(valFun) println(result)

So in the above example, we are passing the value function directly to the foldLeft function. It is just a simple way and more readable to the developer. But i would recommend the first approach to follow.

Examples of Scala foldLeft

Given below are the examples of Scala foldLeft:

Example #1

In this example, we are modifying the string list elements by using the foldLeft function in scala.

Code:

object Main extends App{ val myList: List[String] = List("amit", "sumit", "vinit", "lalti", "minit") println("list before foldLeft function is  :::: ") println(myList) println("list after foldLeft function is  :::: ") println(result) }

Output:

Example #2

In this example, we are finding the sum of all the elements present inside the List collection data structure.

object Main extends App{ val myList: List[Int] = List(100, 200, 300, 400, 500, 600, 700) println("list before foldLeft function is  :::: ") println(myList) var result  = myList.foldLeft(0)(_+_) println("list after foldLeft function is  :::: ") println(result) }

Output:

Example #3

In this example, we are applying different binary operators on the list of integers by using the foldLeft function.

Code:

object Main extends App{ val myList: List[Int] = List(100, 200, 300, 400, 500, 600, 700) println("list before foldLeft function is  :::: ") println(myList) var result  = myList.foldLeft(0)(_-_) println("list after foldLeft function is  :::: ") println(result) var result1  = myList.foldLeft(0)(_*_) println("list after foldLeft function is  :::: ") println(result1) }

Output:

Example #4

In this example, we are finding the maximum value of the collection by using the max function inside the foldLeft function available in scala.

Code:

object Main extends App{ val myList: List[Int] = List(100, 200, 300, 400, 500, 600, 700) println("list before foldLeft function is  :::: ") println(myList) var result  = myList.foldLeft(0)(_ max _) println("list after foldLeft function is  :::: ") println(result) }

Output:

Conclusion

foldLeft functions traverse each element of the collection data structure and help us to perform operations on the element. Thus, it is more reduced and simplified, and untestable to the programmers. Also, it reduces the number of lines of code.

Recommended Articles

This is a guide to Scala foldLeft. Here we discuss the introduction, how the foldLeft function works in scala? And examples respectively. You may also have a look at the following articles to learn more –

How Sort Works In Linq With Different Examples?

Introduction to LINQ Sort

LINQ Sort is used to re-order or re-arrange the given collection of elements into ascending or descending order depends upon the attributes. The sorting operator arranges the sequence of items into ascending or descending order.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

In LINQ it includes five sorting operators they are:

OrderBy

OrderByDescending

ThenBy

ThenByDescending

Reverse

Syntax of LINQ Sort

1. OrderBy

2. OrderByDescending

3. ThenBy

4. ThenByDescending

5. Reverse

var Result_Reverse= userList.Reverse(); How does Sort work in LINQ?

The sorting operator is used to re-arrange the given collection of items in ascending or descending order depending on one or more attributes.

The LINQ Sorting operators are of five different types they are as follows:

1. OrderBy

OrderBy sorting is used to sort the values in the sequence based on a particular field in ascending order or descending order; by default, it sorts elements in ascending order.

Example:

Code:

In the above example, we used the method syntax in OrderBy sort; it sorts the cost of the product it displays the product names based on the Product_Cost wise, by default orderby used ascending order sort.

2. OrderByDescending

OrderByDescending sorts the sequence of elements in descending order. It applies only in the method syntax.

Example:

Code:

3. ThenBy, ThenByDescending

The main purpose of ThenBy and ThenByDescending sorting is for sorting another column along with the prime column. Those both sortings are used for the secondary purpose in LINQ sort; it will be used once the OrderBy and OrderByDescending sort is done; these two are primary sort. ThenBy and ThenByDescending are used after the primary sorting OrderBy and OrderByDescending.

//LINQ SORT – ThenBy Method Syntax

//LINQ SORT – ThenByDescending

It applies extra additional sorting on columns. This sorting will not be applicable in the query syntax; it can be used only in method syntax.

4. Reverse

The final sort is reverse sorting in LINQ; the main purpose of this sort is to display the sequence of the list in the opposite direction. Thus, it can be used in both OrderBy and ThenBy operators, respectively. It does not sort in ascending or descending order; it only displays from the current position in reverse order.

Example:

Code:

Examples of LINQ Sort

LINQ Sorting operator arranges the sequence of items into ascending or descending order. In LINQ it includes five sorting operators.

Let’s see the five sorting operators with examples programmatically.

Example #1 using System; using System.Collections.Generic; using System.Linq; namespace Console_LINQSort { class ProductClass { public string productName { get; set; } public int productCost { get; set; } } class Program { static void Main(string[] args) { _products.Add(new ProductClass { productName = "Speakers", productCost = 2880 }); _products.Add(new ProductClass { productName = "Graphics-Card", productCost = 3000 }); _products.Add(new ProductClass { productName = "Disk-Drive", productCost = 4000 }); _products.Add(new ProductClass { productName = "KeyBoard", productCost = 1540 }); _products.Add(new ProductClass { productName = "Processor", productCost = 7590 }); _products.Add(new ProductClass { productName = "Monitor", productCost = 3250 }); _products.Add(new ProductClass { productName = "Pendrive", productCost = 475 }); _products.Add(new ProductClass { productName = "Pendrive", productCost = 650 }); _products.Add(new ProductClass { productName = "Pendrive", productCost = 870 }); _products.Add(new ProductClass { productName = "Desktop-Table", productCost = 1350 }); Console.WriteLine("ntUsing LINQ - SORTING n"); Console.WriteLine("1. OrderByn"); Console.WriteLine("tProduct-Details n"); Console.WriteLine("tProduct-Pricet Product-Namen"); foreach (var val in result_OrderBy) { Console.WriteLine("t {0}tt {1}", val.productCost, val.productName); } Console.WriteLine("2. OrderBy_Descendingn"); Console.WriteLine("tProduct-Details n"); Console.WriteLine("tProduct-Pricet Product-Namen"); foreach (var val in result_OrderByDesc) { Console.WriteLine("t {0}tt {1}", val.productCost, val.productName); } Console.WriteLine("3. ThenByn"); Console.WriteLine("tProduct-Details n"); Console.WriteLine("tProduct-Pricet Product-Namen"); foreach (var val in result) { Console.WriteLine("t {0}tt {1}", val.productName, val.productCost); } Console.WriteLine("4. ThenBy Descendingn"); Console.WriteLine("tProduct-Details n"); Console.WriteLine("tProduct-Pricet Product-Namen"); foreach (var val in result_ThenByDesc) { Console.WriteLine("t {0}tt {1}", val.productName, val.productCost); } Console.ReadKey(); } } }

Output:

Example #2

The main purpose of this sort is to display the sequence of the list in the opposite direction. Thus, it can be used in both OrderBy and ThenBy operators. It does not sort in ascending or descending order; it only displays from the current position in reverse order.

Code:

using System; using System.Collections.Generic; using System.Linq; namespace Console_LINQSort { class ProductClass { public string productName { get; set; } public int productCost { get; set; } } class Program { static void Main(string[] args) { _products.Add(new ProductClass { productName = "Speakers", productCost = 2880 }); _products.Add(new ProductClass { productName = "Graphics-Card", productCost = 3000 }); _products.Add(new ProductClass { productName = "Disk-Drive", productCost = 4000 }); _products.Add(new ProductClass { productName = "KeyBoard", productCost = 1540 }); _products.Add(new ProductClass { productName = "Processor", productCost = 7590 }); _products.Add(new ProductClass { productName = "Monitor", productCost = 3250 }); _products.Add(new ProductClass { productName = "Pendrive", productCost = 475 }); _products.Add(new ProductClass { productName = "Pendrive", productCost = 650 }); _products.Add(new ProductClass { productName = "Pendrive", productCost = 870 }); _products.Add(new ProductClass { productName = "Desktop-Table", productCost = 1350 }); Console.WriteLine("ntUsing LINQ - Sorting n"); Console.WriteLine("Reverse Sortn"); Console.WriteLine("tProduct-Details n"); Console.WriteLine("tProduct-Pricet Product-Namen"); foreach (var val in result_Reverse) { Console.WriteLine("t {0}tt {1}", val.productName, val.productCost); } Console.ReadKey(); } } }

It just sorts the elements in reversed order from the current sorted list of elements; in this program, we just sort in ascending order based on the cost of the product by using orderby and then Reverse method is used it just prints the reverse order of the current list, it’s an opposite direction of the list.

Output:

Conclusion

In this article, we have seen the usage of different types of Sorting Operators in LINQ. By using those sorting operators OrderBy, OrderByDescending, ThenBy, ThenByDescending and Reverse, we can easily sort our data in our desired way as per our requirement.

Recommended Articles

This is a guide to LINQ Sort. Here we discuss the introduction, how sort works in LINQ? and examples for better understanding. You may also have a look at the following articles to learn more –

Update the detailed information about How Charts Works Inwith Examples? on the Tai-facebook.edu.vn website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!