In Part 2, am going to explain the remaining options of select method. SQL queries allows arithmetic operations in select statement , we can do this in linq select method also.
As you can in the above code am multiplying unitprice with discount and storing it in a new field totalprice which is equivalent to giving alias name for columns in sql queries.
Select method also supports addition, subtraction, division,
Using MAX, MIN, SUM
The code shows the use of max() method of linq. It selects the max ordered, in the same way min() and sum() can also be used.
Using Where Clause
Most of the time we need to select data based on certain conditions. Linq supports conditional selecting. It has where() method which works same as where clause of query. Where method supports multiple conditions. Multiple conditions are specified using logical operators (&&,||).
Using OrderBy
The select data can be ordered ascending or descending by using orderby() and orderbydescending() method respectively.
Example,
Using GroupBy
In certain situations we need to group selected data to get the count of individual type of data. Linq have groupby() method which can be used to achieve this. It groups data and returns an IQueryable
Example,
In the above code, the products are grouped according to categoryid, the first foreach loop iterates through each of the igrouping objects and gets the key, Key is nothing but the field used to group values, in this case it is “categoryid” if the table is grouped on multiple conditions then the no of keys increases.
In IGrouping, the first object is the key, multiple keys are placed using comma. It must be similar to the datatype of the field used to group values.
The nested foreach loop iterates through the actual product table values and displays productname.
Since the return type of groupby() is IQueryable, it can be further queried to get the more specific results. This is shown in the line of codes after comment.
The function produces the output








