IT SHARE EDU
Các loại Cú pháp trong LinQ in c# giới thiệu nhận biết các loại cú pháp. Có 3 loại chính:
- Query syntax
- Method syntax
- Mix mode Query vs Method
Code vidu nhận biết cú pháp linQ
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CuphaplinQ
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//vd có 1 nguồn dữ liệu
int[] arr = { 1, 3, 6, 8, 0, 3, 2 };
private void button1_Click(object sender, EventArgs e)
{
// dùng Query syntax lọc số chẵn trong mảng
var dsschan = from x in arr
where x % 2 == 0
select x;
lstso.Items.Clear();
foreach (var a in dsschan)
{
lstso.Items.Add(a);
}
// lấy phần tử x trong arr với điều kiện x là số chẵn
// x là 1 phần từ nào đó trong arr nội suy kiểu dữ liệu int
}
// cách nhận biết cú pháp 2 method syntax
private void button2_Click(object sender, EventArgs e)
{// where lọc ra method syntax
var dsschan = arr.Where(x => x % 2 == 0);
lstso.Items.Clear();
foreach (var a in dsschan)
{
lstso.Items.Add(a);
}
}
// cách nhận biết cú pháp 3 Mix mode Query vs Method
private void button3_Click(object sender, EventArgs e)
{
// loc ra các số lẻ sắp xếp nó giảm dần
var dsschan = (from x in arr
where x % 2 != 0
select x).OrderByDescending(x=>x);
lstso.Items.Clear();
foreach (var a in dsschan)
{
lstso.Items.Add(a);
}
}
}
}