Trending November 2023 # How Distinct Command Works With Examples # Suggested December 2023 # Top 19 Popular

You are reading the article How Distinct Command Works With 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 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 –

You're reading How Distinct Command Works With Examples

Learn How It Works With Javafx With Examples?

Introduction to JavaFX FXML

JavaFX  FXML is defined as a GUI format with XML-based language launched by Oracle Corporation that enables to compose of the GUIs’ layout or the application of GUIs. The Primary purpose of FXML is to define a user interface. Placing XML mark-up here is to describe a component of UI in the hierarchy structure. A controller takes managing interactions by defining components and link them with them. FXML file has an extension .fxml and it is loaded by FXML Loader by JavaFX,

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

JavaFX FXML is created as below

How does JavaFX FXML work?

JavaFX is used to create the Desktop Application, which allows to code the User-interface by making the application easier. In FXML XML elements are a class, script, property, static. A typical JavaFX FXML works like below:

FXML document has a user interface of an FXML application.

FXML Controller handles all the event handling process.

Next, FXML Loader parses the given FXML document and creates a graph. Simultaneously the Main Class initiates the execution of a Program.

For example, when a user accessing a website, he/she checks with the updated information of their needs; therefore, we need to recompile a code. In such a case FXML controller plays a role.

In this article, I have used NetBeans IDE, which supports JavaFX. This IDE typically provides a visual Layout for designing a UI. Deploying the first JavaFx application is needed. To take up the process:

Java file: This takes up a java code for an application (Main Application)

.fxml file: Here FXML source file is created to define a user interface part.

Below is the NetBeans IDE screenshots that support JavaFX. Here we could see three application files in the name JAVAFXApplication1

The following image shows the application that executes with the button event handlers. FXML specifies two event handlers, namely script and Controller event handlers. FXML Layout file could be created for more parts; this keeps the controller and views independently. And the scene Builder doesn’t need XML directly to work with. The stage is the main container, and the Scene is the UI elements here.

Adding Scripts

mainButton.setText(“press me!”); }

Vbox here is a component that makes a form in a vertical order (child elements). We can insert text, labels, and buttons to create a form Layout. Namespaces are added to the root element.

FXML containing stackPane

Using Border Panel

<HBox prefHeight="110.0" prefWidth="210.0"

 Adding Component inside FXML file

public class load extends VBox implements Initializable { @FXML private void handleAction(ActionEvent eve) { } @Override public void initialize(URL u, ResourceBundle re) { } }

FXML annotation is given as

public class layout @FXML private TextField txt; @FXML private Button btn; @FXML private VBox dataContainer; @FXML private TableView tab; Examples

In this section, we will show you how to use chúng tôi in Net Beans IDE.

The respective Java class is given as

FXMLsample.java

package fxmlsample; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class FXMLsample extends Application { @Override public void start(Stage st) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("FXMLdoc.fxml")); Scene sc = new Scene(root, 200, 215); st.setTitle("FXML Welcome"); st.setScene(sc); st.show(); } public static void main(String[] args) { launch(args); } }

FXMLdoc.fxml

<Text text="Welcome Page" GridPane.columnIndex="0" GridPane.rowIndex="0" <GridPane fx:controller="FXMLdoc.FXML_ctrl"

Next is the controller class with the response to the FXML file for the UI application

FXML_ctrl.java

package FXMLsample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.text.Text; import javafx.scene.control.Label; public class FXML_ctrl { @FXML private Text actiontarget; @FXML protected void handleSubmitButtonAction(ActionEvent event) { actiontarget.setText("Submit the button"); } }

Explanation

The above code section shows to run an FXML application by loading a loader. Similarly, we could see how the components get to each other.

Output:

Features

They have a large set of built-in GUI components like checkboxes; buttons also come with a built-in charts library to create charts.

JavaFX FXML is an XML mark-up language and has a rich set of APIs. It’s a powerful tool and keeps the code easier. Used to develop rich Internet applications using java Files.

JavaFX has CSS styling and gives a declarative layout through FXML.

FXML uses namespaces with the prefix ‘fx’ in which all elements and attributes are assigned. Also, well simple to debug and modify.

Conclusion

This is all about JavaFX FXML. In this article, we had discussed their definition and how it works with JavaFX, along with the examples. Generally, the basics of JavaFX demonstration would not work wells. To build a larger application, we need a system FXML. Therefore, we have explained how it could be used in the development of JavaFX implementation.

Recommended Articles

This is a guide to JavaFX FXML. Here we discuss the definition and how it works with JavaFX, along with the examples and features. You may also have a look at the following 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 Distinct Command Works With 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!