LINQ is stand for Language Integrated
Query. LINQ solves the problem of dealing with very large collections of
data, for which you typically need to select a subset of the collection
for the task your program is performance. LINQ free you from having to
write this extra looping code to filter and sort. It enables you to
focus on the objects that matter to your program. There are two ways to programming query in LINQ: Query Syntax and Method Syntax.
Please examine example of LINQ below:
public partial class Form1 : Form
{
string[] names = { "ain", "bin", "cin", "son", "sik", "fin", "gins", "hin", "iin", "jin", "kin", "lin", "suki" };
public Form1()
{
InitializeComponent();
//------write as Query Syntax ---------
/* this statement is mean select word in array (names) which ordered by ascending */
var queryResults = from n in names orderby n ascending select n;
listBox1.Items.Clear();
//load data into listbox
//load data into listbox
foreach (var item in queryResults)
{
listBox1.Items.Add(item);
}
}
private void btnTestLinQ_Click(object sender, EventArgs e)
{
//--------write as method Syntax----------
//query array string start with letter s
/* this statement is mean select word in array which start with letter s */
var queryResults = names.OrderBy(n => n).Where(n=>n.StartsWith("s"));
listBox1.Items.Clear();
foreach(var item in queryResults){
listBox1.Items.Add(item);
}
}
}
Description:
- In event form load: I query data from array (names) load to listbox by using query method.
- In event onclick of btnTestLinQ: I query data from array(names) load to listbox which i filtered only the word containing letter 's' when click on button Test LinQ by using method query.
Query result with LINQ |
Query Syntax Vs Method Syntax:
- Query Syntax is the way programming query in LINQ, it is generally is easier to read and is simpler to use for the most common query.
- Method Syntax is also the way programming query in LINQ, it is a little bit hard to understand than Query Syntax. However, it has more advantage than Query Syntax because some LINQ capabilities either are not available in Query Syntax, or are just easier to use in the Method Syntax.
Hope you guy enjoy it ;)
Introduce to LINQ in C#
Reviewed by BeiLover
on
3:54 PM
Rating:
No comments: