0

我有多个嵌套的 foreach 循环进行一些处理,如何将此表达式转换为 Linq?

slug.Text = "";
foreach (var script in slugItem.script) {
 foreach (var body in script.body) {
  foreach (var vo in body.vo) {
   foreach (var content in vo.content) {
    foreach (var text in content.text) {
     slug.Text = string.Format("{0}\n{1}", slug.Text, text.Value);
    } } } } }
4

2 回答 2

2
slug.Text = string.Join("\n", slugItem.script.SelectMany(i=>i.body)
                                             .SelectMany(i=>i.vo)
                                             .SelectMany(i=>i.content)
                                             .SelectMany(i=>i.text)
                                             .SelectMany(i=>i.Value));
于 2012-07-04T08:47:26.657 回答
1

为什么要使用 Linq,它会添加什么?但是,我会使用StringBuilder

var slugtext = new StringBuilder();

foreach (var script in slugItem.script) 
{   
    foreach (var body in script.body) 
    {    
        foreach (var vo in body.vo) 
        {     
            foreach (var content in vo.content)
            {      
                foreach (var text in content.text)
                {       
                    slugText.AppendLine(text.Value);
                }
            }
        }
    }
}

 slug.Text = slugText.ToString();
于 2012-07-04T08:57:38.147 回答