Foreach循环到Lambda或更简单的LINQ查询

时间:2016-12-06 11:39:36

标签: asp.net linq foreach lambda attributes

可以将以下代码转换为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] + "|";
            }

1 个答案:

答案 0 :(得分: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<>。但它似乎没有。