Takewhile trong linq c# lọc lấy phần từ đầu tiên
Takewhile là phương thức lọc lấy ra các phần tử đầu tiên có điều kiện thõa mãn. Khi gặp bất cứ một phần từ nào không thỏa mãn nó ngừng ngay. Takewhile nó ngược so với skipwhile là loại bỏ các phần tử khi còn thỏa mãn.
Code hướng dẫn sử dụng hàm takewhile lọc số chẵn
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 hoctakewhile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
List<int> dsint = new List<int>();
Random rd = new Random();
private void btnTao_Click(object sender, EventArgs e)
{
int n = int.Parse(txtTao.Text);
dsint.Clear();
for (int i = 0; i < n; i++)
{
dsint.Add(rd.Next(50));
}
lstGoc.Items.Clear();
dsint.ForEach(x => lstGoc.Items.Add(x));
}
private void btnTakewhile_Click(object sender, EventArgs e)
{
var dstakewhile = dsint.TakeWhile(x => x %2 == 0).ToList();
lstTakewhile.Items.Clear();
dstakewhile.ForEach(x => lstTakewhile.Items.Add(x));
}
}
}
Không có nhận xét nào