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 (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.
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在另一个答案下指出的那样-这也具有不将所有字符串再次存储在内存中的优点。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.