How To Use Distinct And FirstOrDefault Clauses In .NET Using linq.js

Let us see how to use Distinct() and FirstOrDefault() clauses with the help of linq.js in .NET Web Application.

Advantage

  1. It is useful to write simple LINQ queries from Entityframework to client side with LinqJS.
  2. It’s better for validating data at the client side.
  3. Improves performance of the application.

Let’s see one by one,

  1. Distinct() function is different here. 

    C#.NET Code
    1. var FirstNameCollection = myDataArray.Select(x => x.FirstName).Distinct();  
    LinqJS Code
    1. // Retrieves non-duplicate FirstName values.  
    2. var FirstNameCollection = Enumerable.From(myDataArray).Distinct(function(x) {  
    3.     return x.FirstName;  
    4. }).Select(function(FName) {  
    5.     return FName;  
    6. }).ToArray();  
  2. The FirstOrDefault() function is nearly similar.

    C#.NET Code
    1. public class cmbMonthOfWeek {  
    2.     public string cmbMonth {  
    3.         get;  
    4.         set;  
    5.     }  
    6.     public int Id {  
    7.         get;  
    8.         set;  
    9.     }  
    10. }  
    11. List < cmbMonthOfWeek > weekInfo = new List < cmbMonthOfWeek > ();  
    12. weekInfo.Add(new cmbMonthOfWeek {  
    13.     cmbMonth = "First week", Id = 0  
    14. });  
    15. weekInfo.Add(new cmbMonthOfWeek {  
    16.     cmbMonth = "Second week", Id = 1  
    17. });  
    18. weekInfo.Add(new cmbMonthOfWeek {  
    19.     cmbMonth = "Third week", Id = 2  
    20. });  
    21. weekInfo.Add(new cmbMonthOfWeek {  
    22.     cmbMonth = "Fourth week", Id = 3  
    23. });  
    24. var defaultWeekData = (from p in weekInfo where p.Id == 1 select p).FirstOrDefault(); 
    Note

    Here in defaultWeekData, you will get cmbMonth = "Second week".

    LinqJS Code
    1. $scope.cmbMonthOfWeek = [{  
    2.     "cmbMonth""First week",  
    3.     "Id": 0  
    4. }, {  
    5.     "cmbMonth""Second week",  
    6.     "Id": 1  
    7. }, {  
    8.     "cmbMonth""Third week",  
    9.     "Id": 2  
    10. }, {  
    11.     "cmbMonth""Fourth week",  
    12.     "Id": 3  
    13. }, ];  
    14. var defaultWeekData = Enumerable.From($scope.cmbMonthOfWeek).Where(function(x) {  
    15.     return x.Id == 1  
    16. }).FirstOrDefault();  

Note

With defaultWeekData, you will get cmbMonth = "Second week".