You are reading the article How Function Works In Scala With Examples updated in November 2023 on the website Cancandonuts.com. 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 Function Works In Scala With Examples
Definition of Scala FunctionAs the name suggests, Scala Function means a piece of code supposed to do a function. Like any other programming language scala, Function works in the same way. The function is nothing but a way to writing our logic in a separate part, or we can say a function is a group of statements that are responsible for performing some specific task. The function can be used where we have the same logic or repetitive code, so instead of writing the code again and again, we can create one function and call that from everywhere. Scala function is also responsible for performing a specific task.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
How to Define Functions in Scala? defname_of_function ([parametre_list]) : [return_type] = { }Scala Function contained 6 parts while defining; let’s discuss them one by one.
def: It is a keyword that is available in scala. If you want to define any function, we have to use this keyword at the beginning.
name_of_function: This is the user-defined name of the function. It should be similar to the logic or task that the function is going to execute while calling. Also, it should be in a camel-case (lower).
return_type: return type means what we are expecting from the function in return after executing. It can be anything, but it is optional. In java, the default return type is void, and in scale, it is Unit if we do not specify.
parametre_list: This stands for what we are providing to our function while calling. We have to specify the data type of the parameters as well while declaring inside the square brackets []. We will see them into the practice syntax below.
=: This can be used with the return type component. It specifies, if the = is there, it means our function is going to return some value. If not, then no value we want. It is like a default return type function.
function logic: Inside this, we write the whole logic that we want to perform on the calling of function. We can also call the different functions inside this function. Remember body should be enclosed with the {} curly braces.
defcalculateSum ([a:Int, b: Int]) : Int = { return a + b; }This way, we can define it.
How does Function work in Scala?The function is used to perform the task. To use any function, we need to call it. Scala provides us with different ways to call a function, i.e. we can call them directly or by using the class instance.
[instance].name_of_functionor
function(list_parameter)In scala, we have two types of functions like any other programming language.
Parameterized functions: In this type of function, we pass the list of parameters.
Non-Parameterized functions: In this type of function, we do not pass any parameters to function. That will be empty. Also, we can pass any user-defined value as a parameter also.
Let’s take one example to understand its working;
object Main extends App{ calculateSum(10, 20) defcalculateSum(a : Int, b : Int){ var result = a + b ; println("Result is :: "+ result) } }Above we have defined one function name calculateSum, and it is taking two variables, a and b. Both are of the Integer type. Inside the function body, we have written the logic that we want to perform. We are adding these two values, a and b, holding the value into the third variable named result. After that, we are just printing the value that we obtained. But now we have to call this function, so in the above line, we are calling the function b its name and parameter specified. The number of Parameters we passed and the number defined in the function signature should be the same; otherwise, it will give a compile-time error.
Examples of Scala FunctionExamples of (simple function, parameterized function, etc.).
Example #1This example shows the use of functions without parameters.
object Main extends App{ simpleFunction() defsimpleFunction(){ println("This is simple function") println( "without parameter. ") } }Output:
Example #2Code:
object Main extends App{ sum(20 , 50, 100) defsum(x: Int, y : Int, z: Int){ println("This is parameter function") var result = x + y +z println("result obtained is :::" +result) } }Output:
Example #3In this example, we are making a mixed parameter list of a function. This takes integer and string as well.
Code:
object Main extends App{ mixedFunction(20 , 50, 100, "Ajay", "Indore") defmixedFunction(x: Int, y : Int, z: Int, name: String, address: String){ println("This is parameter function") var result = x + y +z println("result obtained is :::" +result) println("Employee name :: " + name) println("Employee address :: " + address) } } Example #4In this example, we are taking a user-defined object and printing its value. We can take any value as a parameter.
Code:
object Main extends App{ var emp1 = new Employee("Amita", 20, 30, "Indore") employeeInfo(emp1) defemployeeInfo(emp : Employee){ println("In this we are taking one user defined parameter.") println("Passing a user value ::") } } class Employee(name: String, Id:Int, Age: Int, address: String){ }Output:
ConclusionFunctions are used to avoid the redundant code or repetitive code. It makes our code looks simple and more understandable. Also, we can easily debug our code and identified the error, if any. These Scala functions are the same as any other programming language. Keep in mind the return type and parameter list or signature of the function while working with them.
Recommended ArticlesWe hope that this EDUCBA information on “Scala Function” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
You're reading How Function Works In Scala With Examples
How Getorelse Function Works In Scala?
Definition of Scala getOrElse
This method is the part of option class in scala. Also, this method exists for both some and none class in scala. What it basically do is it just evaluates the value of the variable and return us the alternative value if the value is empty. This method works on two things success and fail. It will return us the actual value or the default value according to the response we get. This method is used to return an optional value.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Below is the syntax for getOrElse methods as per the scala doc. This method will return us the optional value if the value is coming out to be empty otherwise it will give us the evaluates values or the actual value obtained. We will also see one practice example for better understand of syntax:
Example:
val myVar = toInt("200").getOrElse(10)In the above line of syntax, we are declaring our variable and here we are trying to type case the string into integer and passing one default value to the getOrElse if the value is empty.
How getOrElse Function Works in Scala?As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value. All these classes can be found in the scala. Option package.
Some of the extended class,syper types of option values are as follow see below;
1. Exteded class available in scala for getOrElse method;
IterableOnce[A]
Product
Serializable
2. Linear type available in scala for getOrElse method;
AnyRef
Any
io.Serializable
Product
Equal
3. Some of the known sub classes available in scala for getOrElse method;
None SomeNow we will see one practical example and understand how it internally works;
object Main extends App{ valx:Option[Int] = Some(100) println("value for x is :: " + x.getOrElse(0) ) }In this example, we are creating one Option variable and assigning it a value 100 by using Some class in scala. After this we are using the getOrElse method get the value of the variable. But here we have initialized some value to the variable so the output will be 100 here. If we have not initialized the value the output would be the default value that we have assigned to the getOrElse method. In order to use this method, the variable should be the instance of Option here because we can use this method as the optional value for variable in scala.
This method is used as an optional value provider in the scala if the input is empty.
We can provide any alternative value by using this method.
This method first evaluates the value and then return us the actual or we can say the calculated value.
While using Option class one thing we have to keep in mind is we have two Object Some and None. Some takes value and None means not defined value.
This method follows the success and failure approach which means success if value present fail if not present.
Examples of Scala getOrElseFollowing are the examples are given below:
Example #1In this example we are using the option class in scala to make use of getOrElse method. We have created two Integer variable for this to test.
Code:
object Main extends App{ valy:Option[Int] = None valx:Option[Int] = Some(100) val result1 = x.getOrElse(0) val result2 = y.getOrElse(0) println("value for the variable one is :::") println(result1) println("value for the variable two is :::") println(result2) }Output:
Example #2In this example we are creating the string objects and using getOrElse method with them here.
object Main extends App{ valy:Option[String] = None valx:Option[String] = Some("Hello some value here!!") val result1 = x.getOrElse("No value provided !!") val result2 = y.getOrElse("No value provided !!") println("value for the variable one is :::") println(result1) println("value for the variable two is :::") println(result2) }Output:
Example #3In this example, we are using more than one variable with getOrElse method n scala. By using some and none both class because we cannot directly call them on the normal variable it is not the function for them.
Code:
object Main extends App{ val variable1:Option[Int] = Some(90) val variable2:Option[Int] = Some(90) val variable3:Option[Int] = Some(90) val variable4:Option[Int] = Some(90) val variable5:Option[Int] = None val variable6:Option[Int] = None val variable7:Option[Int] = None val variable8:Option[Int] = None val result1 = variable1.getOrElse(0) val result2 = variable2.getOrElse(1) val result3 = variable3.getOrElse(2) val result4 = variable4.getOrElse(3) val result5 = variable5.getOrElse(4) val result6 = variable6.getOrElse(5) val result7 = variable7.getOrElse(6) val result8 = variable8.getOrElse(7) println("value for the variable one is :::") println(result1) println("value for the variable two is :::") println(result2) println("value for the variable three is :::") println(result3) println("value for the variable four is :::") println(result4) println("value for the variable five is :::") println(result5) println("value for the variable six is :::") println(result6) println("value for the variable seven is :::") println(result7) println("value for the variable eight is :::") println(result8) }Output:
ConclusionSo getOrElse method can we used as an optional or a default value if the input provided is empty. We can use this in a scenario where we have to give some default value for the empty input. Also, it is very easy to use, readable and under stable by the developer, and also it is available for both Some and none class of Option in scala.
Recommended ArticlesWe hope that this EDUCBA information on “Scala getOrElse” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
How Reduce Function Work In Scala With Examples
Introduction to Scala reduce Function
Scala reduces functions to reduce the collection data structure in Scala. This function can be applied for both mutable and immutable collection data structures. Mutable objects are those whose values change frequently, whereas immutable objects are those objects that one assign cannot change itself. Reduce function can be applied to map, sequence, set, list, etc. This function returns a single value from the collection data structure. In reducing function, it merges all the values from the collection data structure and returns on a single value.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Syntax
Below is the syntax of Scala reduce:
Explanation: In the above syntax, we have prepared one collection followed by the reduced function. It takes two parameters on which we can perform our operation. At last, we will obtain one value as output.
How does reduce Function work in Scala?Reduce function reduces the number of elements in the collection data structure. What it does internally is it uses binary operation and merges all the available elements into one single element. We can see how it works internally. Suppose we have one list of elements like 3, 7, 9, 2, 1, 5. Now we will apply to reduce function to generate a single number after adding all the numbers from the list.
1. First, it will take the first element 3. Then it will apply a binary operation on the first and second numbers and merge them to generate the third number.
Now we can have a look at one practical example for beginners for more understanding:
Code:
object Main extends App{ val collection = List(200 , 400, 100, 30, 1000, 500) }Explanation: In this example, we create one collection data structure list. After that, we apply to reduce function on the list to try to find out the max element from the list of elements. This will also return as a single value from the list of elements.
Extended class:
AbstractIterable[(K, V)]
Map[K, V]
Some of the supertype:
Map
Equals
MapFactoryDefaults
MapOps
PartialFunction
AbstractIterable
Iterable
IterableFactoryDefault
IterableOps
IterableOnceOps
IterableOnceOps
Some known classes:
TrieMap
AbstractMap
HashMap
IntMap
ListMap
Longman
Map1
Map2
Map3
Map4
withDefault
TreeMap
TrrSeqMap
VectorMap
AbstractMap
AnyRefMap
CollisionProofHashMap
LinkedHashMap
LongMap
WithDefault
SystemProperties
ListMap
OpenHashMap
reduceLeft
reduceRight
reception
reduceRightOPtion
reduceLeftOPtion
Examples to Implement Scala reduceBelow are the examples mentioned :
Example #1In this example, we find out the sum of all elements present in the collection data structure using a binary operation.
Code:
object Main extends App{ val list1 = List(200 , 400, 100, 30, 1000, 500) println("list before ::") println(list1) println("list after ::") println(result) }Output:
Example #2In this example, we find out the subtraction of all elements present in the collection data structure using a binary operation.
Code:
object Main extends App{ val list1 = List(200 , 400, 100, 30, 1000, 500) println("list before ::") println(list1) println("list after ::") println(result) }Output:
Example #3In this example, we are finding out the multiplication of all elements present into the collection data structure by using a binary operation.
Code:
object Main extends App{ val list1 = List(200 , 400, 100, 30, 1000, 500) println("list before ::") println(list1) println("list after ::") println(result) } Example #4In this example, we find out the division of all elements present in the collection data structure using a binary operation.
Code:
object Main extends App{ val list1 = List(200 , 400, 100, 30, 1000, 500) println("list before ::") println(list1) println("list after ::") println(result) }Output:
Example #5In this example, we are finding out the minimum of all elements present in the collection data structure by using a binary operation.
Code:
object Main extends App{ val list1 = List(200 , 400, 100, 30, 1000, 500) println("list before ::") println(list1) println("list after ::") println(result) }Output:
ConclusionScala reduces function is used to perform the binary operation on the collection elements. We can perform so many types of operations. Also, we can find the maximum and minimum values from the collection using the reduce function. Always remember this reduction will always return a single value as the output of the logic because it will merge all the values from the collection.
Recommended ArticlesWe hope that this EDUCBA information on “Scala reduce” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
Examples On Does Any() Function Works In C++
Introduction to C++ any() Function
Bitset is one of the important class in the C++ library that helps to emulate strings or numbers in the form of a sequence of bits stored like an array where each of the bits is stored at consecutive positions in the array. Since the storage dataset used is an array, each bit can be referenced by a particular index that helps in fast access of elements. Any() method is one of the methods provided in Bitset Class to find if any of the bit present in the array is set that is its value is ‘1’. If none of the bit is set false is returned.
Start Your Free Software Development Course
Syntax:
Before C++11: bool any() const;
Since C++11: bool any() const noexcept;
This method requires no parameters to be passed while calling. Only the reference to one of the objects of Bitset class calls this method for the bitset representation object is holding.
Bool: Determines that the return type for this method is a Boolean, that is either true in case any one of the bit is set otherwise false.
Const: restricts any changes to this method by any of its child classes.
After C++11 this method does not throw any exception, can be inferred using noexcept keyword mentioned in its declaration.
How any() Function Works in C++?A bitset helps to emulate an array of bool where each bit is stored in such a way to use memory efficiently as memory consumed to store a bitset is far less than the storage of Boolean array or vector. Thus it can be inferred the information stored using bitset is stored in a compressed manner, thus helps in enhancing the performance of the array and vector operations on it. The only limitation of using bitset is the size of the array needs to be declared at compile time.
1. Each bit in bitset array can easily be accessed using indexes for eg, obj[3] points to the element stored at index 3 in the bitset from right side.
2. Bitset also gives constructor to get the bitset representation of given string and numbers. Thus one can easily use this class to store the information. It provides various methods to perform operations on the bits such as :-
Count
All
Any
Test
Set
3. When Any() method is triggered for a bitset object, the compiler traverse the whole array of bitset from 0 to N index, where N is declared at compile-time, and checks if the bit is set i.e the value of the bit at that index is 1. If yes it breaks the loop and returns true Boolean otherwise False Boolean. Any() method working is same as loop given below:-
for(int i=0;i<bitsObj.size();i++){ if(bitsObj.test(i)){ return true; break; } else{ return false; } } Advantage of any() Function in C++
All the bitwise operations on bitset can be performed without any type of conversion or casting, which helps enhance the performance and efficiency.
Examples to Implement of C++ any() Function Example #1Let us consider one simple example to understand how any function in bitset works.
Code :
using namespace std; int main() { bool result1 = obj1.any(); if (result1) cout << obj1 << ” has one of its bits set” << endl; else cout << ” None of the bits is set in “<< obj1 << endl; bool result2 = obj2.any(); if (result2) cout << obj2 << “ has one of its bits set” << endl; else cout << “None of the bits is set in ” << obj2 << endl; return 0; }
Output :
Explanation: Here since obj1 10010 has a bit set at 1 and 4th index thus any method returns true for it. But in case of obj2 000000 has none of its bits as set returns false.
Example #2Code :
using namespace std; #define M 32 int main() { cout << “Bitset representation of uninitialised obj1 is ” <<obj1 << endl; cout << “Bitset representation of 16 is ” <<obj2 << endl; cout << “Bitset representation of “00010” is ” <<obj3 << endl; cout << endl; bitarr[3] = 1; bitarr[2] = bitarr[3]; cout << “Bitset representation of array with 2nd 3rd bbits set is “<< bitarr << endl; cout << “Lets check if any of the bit is set in above 4 bitset representations: “; if( obj1.any()) cout<< “obj1: ” <<“TRUE”<<endl ;else cout << “FALSE” <<endl; if( obj2.any()) cout<< “obj2: ” <<“TRUE”<<endl ;else cout <<“FALSE” <<endl; if( obj3.any()) cout<< “obj3: ” <<“TRUE” <<endl;else cout<< “FALSE” <<endl; if( bitarr.any()) cout<< “bitarr: ” <<“TRUE”<<endl; else cout<< “FALSE” <<endl; cout << endl; return 0; }
Output:
Explanation: In the above-given example, M defines the length of the bitset array for all the given bitset objects. Since obj1 is uninitialized thus its value is by default initialized to 0. Second object obj2 is a number -16 that is converted using bitset constructor to its bitset representation. The third object is in the form of bits 00010 and has bit set at index 1. And the fourth index is a bitset array uninitialized, thus stores 0 value in the start but its 2nd and 3rd bit is set at runtime. Any() method is used to find if any of the bit in the given objects is set or not.
ConclusionBitset representation plays an important role as it helps to work with bits representation of string or numbers. And Since the machine understands the language of “0” and “1”, working with this representation improves the performance. Any() is one of the methods provided in this class to find if any of the bit is set in the given bitset object.
Recommended ArticleThis is a guide to C++ any(). Here we discuss the Introduction to C++ any() Function and its Examples along with Code Implementation and Output. you can also go through our suggested articles to learn more –
How Println Works In Kotlin With Examples?
Introduction to Kotlin println
Web development, programming languages, Software testing & others
SyntaxThe kotlin language uses many default keywords, variables, and functions to implement the mobile-based applications, with some pre-defined keywords, including the functions. Like that, println() is the default function for handling and print the statements, which the coder declares.
{ val variablename= values println(“coder statements and ${variablename}””) var var2= values println(“coder statements and $var2”) }
The above codes are the basic syntax for utilising the println() method and its statements used by the kotlin language. Then, based on the user scenario, we can print the outputs on the console screen.
How does println work in Kotlin?
Using the println() method, the coder prints the statements and the outputs the programmer enters, and it depends on the application point of view. The programmer entered all the codes like keywords, variables, functions, and classes that have both primary and secondary classes. Some nested classes concept implements the parent class with the child class, and then it’s called by the specific packages. For each method, both default and customized methods used the println() statements.
The println() method has similar to the print() method but some difference is there like print() method prints the string inside of the quotes and println() method print the strings inside the quotes which is similar like print() method but the mouse cursor which automatically moves to the next line of the console screen. We can use the expressions and catch the exceptions and errors instance whenever it requires like the try-catch statement is used for handling the exceptions block, but the catch and finally blocks to capture and print the exceptions using the print and println() method. And also, when we want to print the variable inside the println() method, we can use the dollar($) symbol followed by either var and val names along with inside of the double-quoted string literals.
Examples of Kotlin printlnGiven below are the examples of Kotlin println:
Example #1Code:
import java.util.Scanner class examp1{ fun demo() { val strinp="Welcome To My Domain its the first example that related to the kotlin println() statement" mlist.add("Please add the first input") mlist.add("Please add the second input") mlist.add("Please add the third input") mlist.add("Please add the fourth input") mlist.add("Please add the fifth input") println("Please follow the below loop iteration") for(vlist in mlist){ println(vlist) } println("Thank you users your mutablelist datas are entered successfully") println(mlist[1]) mlist.add(1,"June") println("We can modify the first mutable list value as mlist.add(1,"June")") for(vlist in mlist){ println(vlist) } mlist.add("July") println("Again we can add one more list values mlist.add("July")") for(vlist in mlist){ println(vlist) } mlist.addAll(2,finp1) println("We can add all the list values into the single list: mlist.addAll(1,finp1)") for(vlist in mlist){ println(vlist) } mlist.addAll(finp) println("We can add all the values and make it to the single list: mlist.addAll(finp)") for(vlist in mlist){ println(vlist) } mlist.remove("July") println("We can remove the specified values: mlist.remove("July")") for(vlist in mlist){ println(vlist) } } } val num = 41.83 println("Your input num is:") println("$num") println("num = $num") println("${num + num}") println(41.83) val sc = Scanner(System.`in`) print("Please enter your input number: ") var il:Int = sc.nextInt() println("You entered input is: $il") var ob=examp1() ob.demo() }Output:
Example #2Code:
import java.util.Date import java.text.SimpleDateFormat class Exam2() { var id: Int = 0 var sname: String = "" var city: String = "" fun demo2(){ val sinp="41,Sivaraman, Chennai" println(sinp) } } enum class Second(var sec: String) { demo("Welcome To My Domain its the second example that related to the kotlin println()"){ override fun sample() { println("Thank you users have a nice day") } }, demo1("We can override the sample method"){ override fun sample() { println("Current month is june") } }, demo2("Again we override the sample method"){ override fun sample() { println("Next month is july") } }; abstract fun sample() fun demo1(svalues: String): String{ return "Have a Nice day users" } } val inp1 = Exam2() var sinp=inp1.demo2() println(SimpleDateFormat("yyyy-MM-ddX").parse("2023-06-22+00")) println("Welcome To My Domain its the second example that related to the kotlin println() method, $sinp") println("Hello users") println(41) println(1234567L) println(0b01001111) println(41.32) println(41.762F) println('a') println(true) println() var st = "Hello users thank you for spenting ur time with us" println(st) println(st) }Output:
In the second example, we used the date format package utilised in the kotlin codes with some operations like integer, string, float, double and boolean datatype values printed on the output console.
Example #3 import java.util.Scanner try { val inpread = Scanner(System.`in`) println("Welcome To My Domain its the third example that related to the kotlin println()") println("Please enter your inputs") var id = inpread.nextInt() println("Your input id is "+id) demo(41,83,lamb) val inpdata = 12 / 4 println(inpdata) } catch (e: NullPointerException) { println(e) } finally { println("finally block always executed whenever try is executing") } println("Have in Nice Day users please try again") } val result = in1 + in2 println(result) }Output:
In the final example, we used the try-catch block for handling the exceptions and performed the arithmetic operations using the lambda expressions.
ConclusionIn kotlin language, we used many default methods, classes, and keywords to implement the application. So all the programming logic will be implemented using some codes like classes and methods eventhough some additional operations are performed, results are printed on the output console by using the print() and println() methods.
Recommended ArticlesThis is a guide to Kotlin println. Here we discuss the introduction, syntax, and working of println in Kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –
How Union Works In Linq With Examples?
Introduction to LINQ Union
Web development, programming languages, Software testing & others
Syntax:
Let’s see the LINQ Union method syntax as follows,
If you are working with complex types of union collection, then you must make use of the IEqualityComparer interface to get an accurate result; otherwise, you will get only the incorrect result.
How does Union work in LINQ?In LINQ Union method it only supports the method syntax; the query syntax will not be available in the union method. The Queryable and Enumerable classes will be acceptable in the union method. The Union operator or method is mainly used to combine the multiple collections into a single distinct collection; it returns only the unique elements; as a result, it removes the duplicate values from the collection. Let’s see one example as follows.
For Example,
Collection X= {20, 40, 60, 80, 100} Collection Y= {20, 40, 70} var _result = X.Union(Y);The result is = {20, 40, 60, 70, 80, 100} in this resultant collection, the elements 20 and 40 appear in both the collection, so in the result, it returns only once because unique elements are only displayed it eliminates the duplications. Let’s see the working flow of the unique method as follows,
static public void Main() { string[] Department1 = { "JAVA", "DOTNET", "PHYTHON", "ANDROID" }; string[]Department2 = { "JAVA", "ANDROID", "DESIGNING" }; var unionResult = Department1.Union(Department2); foreach (var items in unionResult) { Console.WriteLine(items); } } string[]Department1 = { "JAVA", "DOTNET", "PHYTHON", "ANDROID" }; string[]Department2 = { "JAVA", "ANDROID", "DESIGNING" };From this, we have to return only the unique elements from both the collections it removes the duplications from both collections, to get all the elements uniquely, we need to go with the Union () method,
var unionResult = Department1.Union(Department2);It returns only the unique elements from the collection, in which it removes the repeated elements present in the collection it returns only once; let’s check the result here below,
Result is {"JAVA", "DOTNET","DESIGNING", "PHYTHON", "ANDROID"}; Usage of IEqualityComparer InterfaceHere we introduce the IEqualityComparer Interface for the union method because the union method can’t be able to differentiate whether the two types are equal; it does not work with complex types of collection, so it returns the only incorrect result. For this purpose, we have to build a new comparer class to implement IEqualityComparer Interface to get an accurate result. IEqualityComparer Interface has two different methods, GetHashCode and Equals methods; we need to implement both methods compulsory. Let’s see one example for IEqualityComparer interface and lets us assume the Book Class contains BookID and BookName,
{ public bool Equals(Book x, Book y) { if (x.BookID == y.BookID && x.BookName.ToLower() == y. BookName.ToLower()) return true; return false; } public int GetHashCode(Student obj) { return obj. BookID.GetHashCode(); } }
Now can send the BookComparer class in the Union extension method to get the accurate results.
BookList _1.Add(new BookClass { BookID = 1001, BookName = “The Writer” }); BookList _1.Add(new BookClass { BookID = 1002, BookName = ” Success ” }); BookList _1.Add(new BookClass { BookID = 1003, BookName = “Life Secret ” }); BookList _2.Add(new BookClass { BookID = 1002, BookName = “Success” }); BookList _3.Add(new BookClass { BookID = 1005, BookName = “Team Lead ” }); var _resultUnion = BookList _1.Union(BookList _2, new BookComparer()); foreach (BookClass res in _resultUnion) Console.WriteLine(res. BookName);
The result will be” The Writer, Success, Life Secret, Team Lead,” it returns only the unique elements from the collection, in which it removes the repeated elements.
ExampleCode:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Console_LINQUnion { class Linq_Union { internal class DoctorClass { public int DoctorID { get; set; } public string DoctorName { get; set; } } { public bool Equals(DoctorClass a, DoctorClass b) { if(a.DoctorID==b.DoctorID&&b.DoctorName.ToLower()==b.DoctorName.ToLower()) { return true; } return false; } public int GetHashCode(DoctorClass obj) { return obj.DoctorID.GetHashCode(); } } public class Program { public static void Main(string[] args) { DoctorList_1.Add(new DoctorClass { DoctorID = 1001, DoctorName = "Smith" }); DoctorList_1.Add(new DoctorClass { DoctorID = 1002, DoctorName = "Rio" }); DoctorList_1.Add(new DoctorClass { DoctorID = 1003, DoctorName = "Dev" }); DoctorList_1.Add(new DoctorClass { DoctorID = 1004, DoctorName = "Jack" }); DoctorList_1.Add(new DoctorClass { DoctorID = 1005, DoctorName = "Ricky" }); DoctorList_2.Add(new DoctorClass { DoctorID = 1002, DoctorName = "Rio" }); DoctorList_2.Add(new DoctorClass { DoctorID = 1003, DoctorName = "Dev" }); DoctorList_2.Add(new DoctorClass { DoctorID = 1007, DoctorName = "Peter" }); DoctorList_2.Add(new DoctorClass { DoctorID = 1009, DoctorName = "Raj" }); DoctorList_2.Add(new DoctorClass { DoctorID = 1001, DoctorName = "Smith" }); var _resultUnion = DoctorList_1.Union(DoctorList_2, new DoctorComparer()); Console.WriteLine("USING LINQ-UNION WITH IEqualityComparer"); Console.WriteLine("List of Unique Doctor-Namesn"); foreach (DoctorClass val in _resultUnion) Console.WriteLine(val.DoctorName); Console.ReadLine(); } } } }Output:
ConclusionThe article LINQ Union essentially used to combine the collection of elements and returns distinct elements; as a result, when working on complex types of huge data, we need to implement the IEqualityComparer Interface. I hope the article helps out without any doubt by seeing the examples programmatically.
Recommended ArticlesThis is a guide to LINQ Union. Here we discuss the Introduction, syntax, How Union works in LINQ along with Examples and code implementation. You may also have a look at the following articles to learn more –
Update the detailed information about How Function Works In Scala With Examples on the Cancandonuts.com 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!