Monday, July 7, 2014

Code Optimization with LINQ

What is LINQ ?
Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.
(Definition from : msdn)

LINQ With If  Else

//LINQ conditional If
            //if text in textBox1 is a pop up message that found A else pop up not A
            //Usual code
            //if (textBox1.Text.Equals("A"))
            //{
            //    MessageBox.Show("Found 'A'");
            //}
            //else
            //{
            //    MessageBox.Show("Not 'A'");
            //}
            var d = textBox1.Text.Equals("A") ? MessageBox.Show("Found 'A'") :MessageBox.Show("Not 'A'");

With LINQ simple If Else condition is just single line code. isn't it amazing

Getting Elements from User Interface

My interface has four TextBoxes and I need to popup every Textboxe's Text where it strts from 'A' letter.














//Add all items starts with 'A' to List
            var  selectedBoxes = MainGrid.Children.OfType<TextBox>().Where(x=> x.Text.StartsWith("A")).ToList();
            //pop up them
            foreach (var item in selectedBoxes)
            {
                MessageBox.Show(item.Text);
            }


Like this you can traverse any Collection on C# and filter.

And simply Order the elements in Collections with Order By function in LINQ

var  selectedBoxes = MainGrid.Children.OfType<TextBox>().Where(x=> x.Text.StartsWith("A")).OrderBy(x=> x.Text).ToList();

Select
 Just take each of Dealer contract and dealer as two tables in DB

var dealerContracts = DealerContact.Join(Dealer,
                                 contact => contact.DealerId,
                                 dealer => dealer.DealerId,
                                 (contact, dealer) => contact);





Enjoy...




0 comments: