IT SHARE EDU
Hàm find là hàm tìm kiếm và trả về phần tử đầu tiên trong danh sách có nhiều phần tử cần tìm.
Sau đây là code hướng dẫn sử dụng hàm find trong 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 Hocfind
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List dsdouble = new List();// Tạo dữ liệu tìm kiếm tập double
List dsSP = new List();// Tạo dữ liệu tìm kiếm tập dữ liệu
private void Form1_Load(object sender, EventArgs e)
{
dsSP = new List();
dsSP.Add(new SanPham() { Ma = “SP1”, Ten = “Ken”, Gia = 15000 });
dsSP.Add(new SanPham() { Ma = “SP2”, Ten = “333”, Gia = 16000 });
dsSP.Add(new SanPham() { Ma = “SP3”, Ten = “Sai Gon”, Gia = 17000 });
dsSP.Add(new SanPham() { Ma = “SP4”, Ten = “Tiger”, Gia = 11000 });
lvSanPham.Items.Clear();
dsSP.ForEach(x =>
{
ListViewItem lvi = new ListViewItem(x.Ma);
lvi.SubItems.Add(x.Ten);
lvi.SubItems.Add(x.Gia + “”);
lvSanPham.Items.Add(lvi);
}
);
}
private void btnTim_Click(object sender, EventArgs e)
{
double s = double.Parse(txtTim.Text);
double kq = dsdouble.Find(x => x == s);
MessageBox.Show(kq + “”);
}
private void btnLuuDS_Click(object sender, EventArgs e)
{
int x = int.Parse(txtN.Text);
Random rd = new Random();
for (int i = 0; i < x; i++)
{
double n = Math.Round(rd.NextDouble() * 100, 2);
dsdouble.Add(n);
}
lstSo.Items.Clear();
dsdouble.ForEach(y => lstSo.Items.Add(y));
}
private void button1_Click(object sender, EventArgs e)
{
double gia = double.Parse(txtTimSp.Text);
SanPham kq = dsSP.Find(x => x.Gia == gia);
if (kq!=null)
{
MessageBox.Show(“Tìm Thấy Sản Phẩm:” + kq.Ten+ “:Giá” +kq.Gia);
}
else
{
MessageBox.Show(” không tìm thấy”);
}
}
}
}
// Tạo lớp SanPham:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hocfind
{
public class SanPham
{
public string Ma { get; set; }
public string Ten { get; set; }
public double Gia { get; set; }
}
}