Skip to main content

Posts

Showing posts with the label LINQ

Using LINQ concatenate unique items of two List and Sort them.

In this post I’ll show how you can combine unique items of two List < string > and then Sort them with the help of LINQ. Let’s take two List < string > contains employee names: List < string > empNameList1 = new List < string >() {     "Sandeep" ,     "Ashwani" ,     "Ashish" ,     "Saurav" }; List < string > empNameList2 = new List < string >() {     "Rahul" ,     "Sachin" ,     "Sandeep" ,     "Yuvraj" }; As you can see one name is common in both employee lists, so let’s write LINQ statement ( using the Enumerable .Concat method ) to get unique names and then sort them and finally print all the sorted unique names by looping through it. // Concatenate Unique Names of two List<string> and then sort. var finalNameList = empNameLis...

Different ways of String Reversal in C#

As you may be aware C#'s string class don’t have a Reverse() function by default, so let’s discuss different ways to reverse a given string: Using manual reversal way: The traditional way is to reverse a string by manually looping through it character by character and creating a new string. string inputStr = "This is test string" ; string outputStr = "" ; for ( int i = inputStr.Length - 1; i >= 0; i--) {     outputStr += inputStr[i]; } One thing to remember though, if you are using this approach to reverse a large string then you should use StringBuilder to create output string instead of string because a string instance is immutable and you cannot change it after it was created. Any operation that appears to change the string instead returns a new instance. Using Array.Reverse(): The second approach we can reverse a string is with the inbuilt Array.Reverse() method of Array class. st...

Ordering data by more than one column in LINQ query

In this post I’ll show how you can apply ordering on the multiple columns in LINQ query. If you know LINQ basics, you must be aware that with the help of .OrderBy(x => x.Columnname) in the LINQ query we can order data of the source collection. So many of the novice developers use the same function twice as mentioned below and thinks that will do the ordering on the multiple columns. var students = context.Students                 .OrderBy(x => x.Name)                 .OrderBy(x => x.ClassName); But that is not the solution and LINQ query always does the order by the column you specified in the last OrderBy() method. We can do order by on more than one columns using lambda expressions as well as in traditional LINQ query. Mentioned below are two solutions to achieve using Lambda and t...

System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException: Operation is not valid due to the current state of the object.

You might have sometime faced the below exception while attempting to update an entity property: System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException: Operation is not valid due to the current state of the object. Reason: After looking into the issue I found that this error occurs when an attempt is made to change a foreign key when the entity is already loaded. In this case, I was trying to assign a value to the foreign key property, and an exception is thrown as foreign key fields and association properties don’t match, when changes are submitted. In such a scenario there are two values, one in the foreign key field or the one on the other side of the relationship and it doesn’t know which value is correct, and as a result exception is thrown. Solution: To avoid the exception the best way to update the relationship is by changing the association property and not the foreign keys. And then it will automatically keep the foreign keys in sync when you assign the association prop...

C#: Understand about IEnumerable vs. IQueryable vs. ICollection vs. IList

In this article we’ll understand about the interfaces ( IEnumerable, IQueryable, ICollection and IList) available for holding and querying the data. IEnumerable:   ·          IEnumerable exists in System.Collections Namespace. ·          IEnumerable is most generic item of all and a core interface which is used to iterate over collection of specified type. ·          IEnumerable provides Enumerator for accessing collection. ·          IEnumerable is forward only collection likes LinkedList. It doesn’t move between items or backward, i.e. one can't get at fifth item without passing first four items. ·          It is read-only collection and it doesn't support add or remove items. ·          IEnumerable is best to query data from ...

LINQ: Overview of LINQ and it's advantages and disadvantages

Overview of LINQ: LINQ stands for Language Integrated Query, which is descriptive for where it's used and what it does. LINQ is used for querying data. Here I used the generic term "data" and didn't specified type of data. That's because LINQ can be used to query many different types of data, including SQL, XML, and even objects. It is a Microsoft programming model and methodology that gives formal query capabilities into Microsoft .NET-based programming languages (mainly in C# and VB.Net). LINQ Syntax: LINQ queries can be written through standard query expression or through Lambda expressions. Query expression syntax: var items = from item in Items where item.Price > 10 select item; Lambda expression syntax: var items = Items.Where(c => c.Price > 10).Select(c => c); Type of LINQ: Various type of LINQ available is: ·          LINQ to SQL ·      ...

LINQ: Grouping Data in LINQ using Group By

In this post I’ll explain how one can group data using LINQ GroupBy. GroupBy can be applied on different data types like Generic List, XML, DataTable etc. Syntax of Group By: var result= from c in <collection>     group c by c.<property> into g     select new     {         Key=g.Key,         Value=g     }; LINQ Grouping return partitioned sets of data from a collection based on a given key value, i.e. group employees by designation as: var query = from c in employees         group c by c.Designation; //or same statement can be written in Lambda expression as: var query = employees.GroupBy(c => c.Designation); GroupBy Result: Let’s understand result returned by LINQ grouping operation. The return collection fro...