[英]Lambda Expression doesn't work for filtering obj in a list
User select month, and dynamically 4 textbox + a button (save row) for each day will be drawn; 用户选择月份,每天将动态绘制4个文本框+一个按钮(保存行); every textbox has the textbox.Tag = day who refers.
每个文本框都有文本框。Tag=引用的日期。
When user click on save row I will it to select only the textboxes of the corresponding row (expecting 4 textboxes). 当用户单击保存行时,我将只选择相应行的文本框(预期有4个文本框)。
code that generate the textboxes: 生成文本框的代码:
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);
I try this: 我尝试这样:
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
Any help is very appreciated ^_^ 任何帮助都非常感谢^ _ ^
You are comparing two object
directly, and by default this will be done by references comparison. 您正在直接比较两个
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
You want to compare the value of these date instead: 您想比较这些日期的值:
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.