0

I am currently returning a list of lists (List<List<string>>) from await getWorlds() and right now I am looping through each one of them, and getting the first entry in each list.

I just wonder if there is another way I can quickly add all of them directly into Worlds with .AddRange or something?

Here is my code:

var worlds = await getWorlds();
foreach (var w in worlds)
{
    Worlds.Add(w[0]);
}

Any way to shorten this to something smaller? Like Worlds = worlds.AddRange([0]); or something? I just want to get the first entry [0] and add each one to the Worlds. I'm just looking to see if there's a cleaner way of writing my code. I have not managed to find any example.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Lee Cheung
  • 101
  • 2
  • 9

2 Answers2

3

You can do this:

var worlds = await getWorlds();
Worlds.AddRange(worlds.Select(w => w[0]));

Though I don't see why the foreach was so bad.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 1
    Perfect! Thank you!!!! I was just looking for best-practices. I am new in C# and I just try to write as little code as possible that does the job for me. Would it even be possible to put it all in one line? and switch `worlds.` to `await getWorlds().`? or something – Lee Cheung Sep 04 '18 at 13:28
  • 3
    @Lee The smallest amount of code is not always the best, it can make it unreadable or hard to understand. Sometimes a simple loop is the best, especially as this code is doing basically the same thing but hiding the loop from you. – DavidG Sep 04 '18 at 13:31
  • The main thing to remember with stuff like this is that the compiler will likely end up optimising it to the same code underneath anyway - you will almost certainly not achieve anything in terms of performance or efficiency by obsessing over this sort of thing... – GPW Sep 04 '18 at 13:34
  • Something like this is starting to get difficult to read: `Worlds.AddRange((await getWorlds()).SelectMany(w => w.Take(1)))`. – Enigmativity Sep 04 '18 at 13:35
  • I see. Thanks guys for your help and explanations! I really appreciate it! :) – Lee Cheung Sep 04 '18 at 13:38
2

This is not quite what you're looking for, but you could do this to add all instances of items in all the sub-lists too, rather than just the first one.. (this will flatten the list into a single list of items)

var worlds = await getWorlds();
Worlds.AddRange(worlds.SelectMany(w=>w));
GPW
  • 2,528
  • 1
  • 10
  • 22