[英]Lambda Expression doesn't work for filtering obj in a list
用戶選擇月份,每天將動態繪制4個文本框+一個按鈕(保存行); 每個文本框都有文本框。Tag=引用的日期。
當用戶單擊保存行時,我將只選擇相應行的文本框(預期有4個文本框)。
生成文本框的代碼:
foreach (DateTime day in monthDays)
{
var t1 = new TextBox();
t1.Location = new Point(Origin.X + 90, Origin.Y + 30 * Ycounter);
t1.Size = new Size(40, 25);
t1.MaxLength = 5;
t1.Tag = day;
AutoControls.Add(t1);
Controls.Add(t1);
我嘗試這樣:
private void SaveButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
DateTime d = (DateTime)b.Tag;
List<TextBox> t = new List<TextBox>(AutoControls.OfType < TextBox());
//Autocontrols it's the list with ALL the dynamically generates controls in that form.
var g = t.Where(x => x.Tag == b.Tag); // expecting 4 textboxes, but returns 0
var g = t.Where(x => x.Tag == b.Tag).ToList(); // 0
var g = t.FindAll(x => x.Tag == b.Tag); //returns 0
任何幫助都非常感謝^ _ ^
您正在直接比較兩個object
,默認情況下,這將通過引用比較來完成。
// this for example will never be true, even if today is 20190613
// because they are 2 different instances
(object)new DateTime(2019, 06, 13) == (object)DateTime.Today
您想比較這些日期的值:
t.Where(x => x.Tag is DateTime date && date == d)
List<Control> RecordData = Controls.Cast<Control>().Where(x => x.Tag is DateTime date && date == d).ToList();
我已經從Xiaoy312的建議(感謝^^)開始,並在類似的線程上閱讀了有關Cast命令的內容,從而創建了此代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.