Take trong linq lấy n phần tử đầu tiên
Take là lọc ra n phần tử đầu tiên trong một tập danh sách thỏa mãn điều kiện nào đó.
Code thực hành take lấy ra 10 số đầy tiên trong tập danh sách.
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 HocTake
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
List<int> dsintGoc = new List<int>();
Random rd = new Random();
private void btnTaods_Click(object sender, EventArgs e)
{
int n = int.Parse(txtTaods.Text);
for (int i = 0; i < n; i++)
{
dsintGoc.Add(rd.Next(50));
}
lstGoc.Items.Clear();
dsintGoc.ForEach(x => lstGoc.Items.Add(x));
}
private void btnTake_Click(object sender, EventArgs e)
{
int ntake = int.Parse(txtTake.Text);// nếu giá trị nhập vào lớp hơn phần từ trong tập dữ liệu sẽ lấy hết
var dstake = dsintGoc.Take(ntake).ToList();
lstLoc.Items.Clear();
dstake.ForEach(x => lstLoc.Items.Add(x));
}
}
}
Không có nhận xét nào