Getting an array of strings from an array of objects

I have an array of Tag objects

class Tag
{
 public string Name;
 public string Parent;
}

I want the code to return a list of tag names as an array of strings

+3
source share
6 answers
var names = from t in tags
            select t.Name;

Something like this will give you IEnumerable over the names, just use .ToArray()it if you are not an array of them.

+5
source

How about just:

var tags = new List<Tag> {
  new Tag("1", "A"), 
  new Tag("2", "B"), 
  new Tag("3", "C"), 
};

List<string> names = tags.ConvertAll(t => t.Name);

There is no need for Linq, and if you need an array, call ToArray().

+6
source

IEnumerable. linq foreach

0
 return (from Tag in MyTagArray select Tag.Name).ToArray();
0
string[] tagArray = (from t in tagList select t.Name).ToArray();
0

, - :

public List<string> GetNamesOfTag(List<Tag> tags)
{
   List<string> Name = new List<string>();
   foreach(Tag item in tags)
   {
     Name.Add(item.name);
   }

   returns Name;
}
0

Source: https://habr.com/ru/post/1716964/


All Articles