0

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.

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That has the advantage over the string.Join solutions of not bringing all of the strings into memory at the same time; it streams them to the output, thus resulting in earlier items being seen earlier, rather than waiting for the last item to be processed.
4
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
));

5 Comments

ummm appreciate the answer but could it be in the form of a query ?
@WinCoder: Queries can only be used to query data, not take side-effects. Or do you mean query comprehension syntax as opposed to direct extension method calls?
yup query comprehension syntax
@WinCoder: Here you go.
ahhh that's better now to understand it.
2

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 :)

Comments

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

However not much LINQ here ;), as noted in the comments, just more concise :) Also, as noted by Servy under the other answer - this also has the advantage of not joining and storing all the strings in memory again.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.