首页 > 解决方案 > Lambda 表达式不适用于过滤列表中的 obj

问题描述

用户选择月份,每天动态绘制4个文本框+一个按钮(保存行);每个文本框都有 textbox.Tag = day who引用。

当用户单击保存行时,我将只选择相应行的文本框(预期 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 

非常感谢任何帮助^_^

标签: c#winformslambda

解决方案


您正在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)

推荐阅读