【问题标题】:Foreach loop to Lambda or simpler LINQ queryForeach 循环到 Lambda 或更简单的 LINQ 查询
【发布时间】:2017-04-21 00:57:56
【问题描述】:

下面的代码能否转换为 lambda 表达式或更简单的 LINQ 查询

string str = "";
foreach (string key in (FindControl("Q" + QNo + "AnswerTA") as HtmlTextArea).Attributes.Keys)
              {
                str += key +","+ (FindControl("Q" + QNo + "AnswerTA") as HtmlTextArea).Attributes[key] + "|";
            }

【问题讨论】:

    标签: asp.net linq foreach lambda attributes


    【解决方案1】:

    您当然可以将其简化为:

    var control = FindControl("Q" + QNo + "AnswerTA") as HtmlTextArea;
    
    string str = "";
    foreach (string key in control.Attributes.Keys)
    {
      str += key +","+ control.Attributes[key] + "|";
    }
    

    但是任何 LinQ 语句都会占用更多代码,而且对我来说看起来更混乱。

    string str = control.Attributes.Keys.Select(key => key +","+ control.Attributes[key] + "|")
                                        .Aggregate(string.Empty, (c, n) => c + n);
    

    如果只有 AttributeCollection 为它的对实现 IEnumerable<> 就好了。但似乎没有。

    【讨论】:

    • 第二条语句给出编译时错误“icollection 不包含 select 的定义”
    • hm,也许你错过了 System.Linqusing 语句,但也许这些类太老了,以至于它们没有实现正确的接口。
    • 我正在使用 System.Linq
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    相关资源
    最近更新 更多