简体   繁体   English

LINQ表达式而不是嵌套的foreach循环

[英]LINQ expression instead of nested foreach loop

So i have List whose each element is a string array 所以我有列表,其每个元素是一个字符串数组

List<string[]> TokenList = new List<string[]>();

I want to display each element in the array for every array in the list. 我想为列表中的每个数组显示数组中的每个元素。 and for that i use a nested foreach loop. 为此,我使用了嵌套的foreach循环。

foreach (var temp in pro.TokenList)
        {
            foreach (var s in temp)
            {
                Console.WriteLine(s);
            }
        }

Now i am trying to use LINQ in my programs and i was wondering what kind of LINQ query would be used to achieve the same desired result. 现在,我正在尝试在程序中使用LINQ,我想知道哪种LINQ查询将用于实现相同的期望结果。

I'd rather keep it simple: 我宁愿保持简单:

// select all sub-strings of each TokenList into 1 big IEnumerable.
var query = pro.TokenList.SelectMany(item => item);

// display all strings while iterating the query.
foreach(var s in query)
    Console.WriteLine(s);

It's funny that people combine many statements, but it will be less readable. 人们组合了许多语句很有趣,但是它的可读性较差。

Console.WriteLine(String.Join(Environment.NewLine, 
    pro.TokenList.SelectMany(s => s)
));

Or, 要么,

Console.WriteLine(String.Join(Environment.NewLine, 
    from arr in pro.TokenList
    from s in arr
    select s
));

Try to do this: 尝试这样做:

Console.WriteLine(String.Join(Environment.NewLine, 
    pro.TokenList.SelectMany(s => s)
));

This should work. 这应该工作。 If it doesn't add a comment :) 如果没有添加评论:)

pro.TokenList.ForEach(temp => Array.ForEach(temp, Console.WriteLine));  

但是,这里的LINQ并不多;),如注释中所述,只是更加简洁:)另外,正如Servy在另一个答案下指出的那样-这也具有不将所有字符串再次存储在内存中的优点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM