Let us see how to use Distinct() and FirstOrDefault() clauses with the help of linq.js in .NET Web Application.
Advantage
- It is useful to write simple LINQ queries from Entityframework to client side with LinqJS.
- It’s better for validating data at the client side.
- Improves performance of the application.
Let’s see one by one,
- Distinct() function is different here.
C#.NET Code
- var FirstNameCollection = myDataArray.Select(x => x.FirstName).Distinct();
LinqJS Code
-
- var FirstNameCollection = Enumerable.From(myDataArray).Distinct(function(x) {
- return x.FirstName;
- }).Select(function(FName) {
- return FName;
- }).ToArray();
- The FirstOrDefault() function is nearly similar.
C#.NET Code
- public class cmbMonthOfWeek {
- public string cmbMonth {
- get;
- set;
- }
- public int Id {
- get;
- set;
- }
- }
- List < cmbMonthOfWeek > weekInfo = new List < cmbMonthOfWeek > ();
- weekInfo.Add(new cmbMonthOfWeek {
- cmbMonth = "First week", Id = 0
- });
- weekInfo.Add(new cmbMonthOfWeek {
- cmbMonth = "Second week", Id = 1
- });
- weekInfo.Add(new cmbMonthOfWeek {
- cmbMonth = "Third week", Id = 2
- });
- weekInfo.Add(new cmbMonthOfWeek {
- cmbMonth = "Fourth week", Id = 3
- });
- 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
- $scope.cmbMonthOfWeek = [{
- "cmbMonth": "First week",
- "Id": 0
- }, {
- "cmbMonth": "Second week",
- "Id": 1
- }, {
- "cmbMonth": "Third week",
- "Id": 2
- }, {
- "cmbMonth": "Fourth week",
- "Id": 3
- }, ];
- var defaultWeekData = Enumerable.From($scope.cmbMonthOfWeek).Where(function(x) {
- return x.Id == 1
- }).FirstOrDefault();
Note
With defaultWeekData, you will get cmbMonth = "Second week".