Search Unity

[Solved] Class list to string array, Linq?

Discussion in 'Scripting' started by imtehQ, Jun 15, 2018.

  1. imtehQ

    imtehQ

    Joined:
    Feb 18, 2013
    Posts:
    232
    Code (CSharp):
    1.     public class Player
    2.     {
    3.         public string Name;
    4.         public int level;
    5.     }
    6.  
    7. public List<Player> players = new List<Player>();
    8.  
    How i would like a string array of all the player names, first i was thinking like:
    Code (CSharp):
    1. return players.SelectMany(p => p.Name).ToArray();
    But this will return a Char[] not a string array..
    What im i missing?

    Note: Yes i did google for about 30 minutes but did not find the answer...
     
  2. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,998
    If you're making a game and just want to get it done: foreach(Player p in players) playerNames.Add(p.name);
     
  3. imtehQ

    imtehQ

    Joined:
    Feb 18, 2013
    Posts:
    232
    Hehe yes thats what i had first, but must be a better way.
     
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    You want Select, not SelectMany.

    The difference is:

    Code (csharp):
    1. //assume player has an inventory:
    2.  
    3. public class Player {
    4.     public string name;
    5.     public int level;
    6.     public List<Item> inventory;
    7.  
    8.     void Example(List<Player> players) {
    9.         //Select would just grab an IEnumerable of all the inventories
    10.         IEnumerable<List<Item>> inventories = players.Select(player => player.inventory);
    11.  
    12.         //While SelectMany flattens the inventoryies, and gives you the items:
    13.         IEnumerable<Item> items = players.SelectMany(player => player.inventory);
    14.     }
    15. }

    What happens when you SelectMany the name is that a string is a char array, so those arrays gets flattened into one long array.
     
  5. imtehQ

    imtehQ

    Joined:
    Feb 18, 2013
    Posts:
    232
    Thank you, that's what i needed, for some reason i was thinking select only selected one item.
     
  6. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,998
    Depends on better. I'm pretty sure a simple loop runs faster -- it's doing less work than Linq. But even in games speed isn't that important in 90% of the code.

    Linq might be a tiny bit less error-prone. And more readable _if_ everyone knows those commands -- the "Select" would tend to jump out.