Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Wednesday, 17 July 2013

Differentiate between 'All' and 'Any' Operators in LINQ.

In LINQ, All operator is  to check whether all the elements met the specific condition or not. While Any operator checks whether there is any element exist in the collection or not.


For Example:

int array={1,2,3,4,5};

bool result=array.All(i=>i < 6); here it will check the elements and returns true.

Similarly,

bool result= array.Any( ); // here it checks whether the collection has any elements and returns true.


Hope you Enjoyed!

Monday, 15 July 2013

The Use of ALL Operator in LINQ

Today, I came across the All operator in LINQ. This operator returns bool value rather than records after condition is satisfied. The operator will be highly helpful when you need some kind of validation to find unique data. for e.g. Checking the existing email  or UserID registered and so on.


Lets Go with a Example to do the Task:

int [] array = { 1,2,3,4,5 };

bool result = array.All(value => value > 2 );

Console.WriteLine(result);  // Here it will print False since it will check all the values and                                         // all the values must be grater than 2.


 result = array.All(value => value < 6 );
Console.WriteLine(result); // Here it will print True since it will check all the values and                                          // found all values are less than 6.


Hope it helps you!

Monday, 22 April 2013

Reading a CSV file with Linq


A simple single line of code  to read the CSV file in Linq:

rawFile = (from line in File.ReadAllLines(fileName).AsParallel()
            select line.Split(',')).ToList();

Happy Coding!

Thursday, 31 January 2013

How to show the content of a Multiselect List in a sorting order using LINQ


Here is the code below to sort the multiselect list box content in sort order.

Here I am getting the states list and binding it to a multi select List Box.
         public static MultiSelectList GetStatesList(bool selected = false)
        {

            List<string> list = new List<string>();
            if (selected)
                list = RetailManager.GetAllStateList();
            return new MultiSelectList(list.OrderBy(s => s));
        }


The trick lies here i.e s=>s does the task. How it is doing is that internally it is comparing s[i] with s[j].

Thursday, 24 May 2012

IEnumerable.Count() is a bad style of Coding, Why?

IEnumerable<Participant> participants=GetParticipants();

if(products.count()==0)
{
       SomeControls.Visible=false;
}
else
{
     SomeControls.Visible=true;
}
The wrong thing with the above code is that Count() is a Linq extension Method that literally iterates through every item in an  enumerable( here it is participants). In other words it won't short circuit after it finds more than zero items and will continue iterating through every single item. And while, that one may be fast operation in Dev environment but it will be a slow process in production. This is because of Linq's deferred Execution.

How we can refine the above Code

The above Code can be refined by changing it into as:
IEnumerable<Participant> participants=GetParticipants();

if(products.Any())
{
       SomeControls.Visible=false;
}
else
{
     SomeControls.Visible=true;
}

In the above code once the expression finds more than one item, it simply stops iterating and just increasing the Optimization time.

Happy Coding.........!

Tuesday, 20 September 2011

Updating the database without querying it using LINQ and C#

One can update the Database using LINQ i.e. By querying first and then go for update.

However, one can go for update directly rather then querying it and then go for update.

HOW to DO it

For ex: In my case I want to update the QuestionTable  of my database(say Quizzana)  on the the update button click event.

Follow the Steps below--------->

Step-1: 
Create a DataBase context as ( dbConnectionDataContext db = new dbConnectionDataContext( );)

Step-2:
 Now create an object of the type which you want to update, here mine is the question table so I had created a Question object and kept the Address in the var variable named  ' q ' but you can keep in a same class variable.

Step-3:
Now point the field on which basis you want to make update, here I am using Qno .

Step-4:
Then attach the Object created to the corresponding table of the DataContext and then only go for the updates otherwise it throw the exception.

Step-5:
Now refresh the DataContext as--- db.Refresh(System.Data.Linq.RefreshMode.KeepChanges,q); where Refresh is the Method that takes the RefreshMode and the object of the Object to update it.

Step-6:
Now you can call the SubmitChanges( ) to Update the Table of the Database using the data context.

The Code is here Below:-

 public void btnUpdate_Click(Object sender, eventargs e)
{

           dbConnectionDataContext db = new dbConnectionDataContext();
             var q = new Question();
              q.Qno = qno;
               db.Questions.Attach(q);
               q.Qns = tbQns.Text.Trim(); ;
                try
             {
                 db.Refresh(System.Data.Linq.RefreshMode.KeepChanges,q);
                 db.SubmitChanges();
                 MessageBox.Show(qno+" no. upated successfully");
                 this.Close();

             }
              catch (Exception ex) { MessageBox.Show(ex.ToString()); }
        }