leora
leora

Reputation: 196439

Getting an array of string from an array of objects

i have an array of Tag objects

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

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

Upvotes: 3

Views: 311

Answers (6)

Cihan Yakar
Cihan Yakar

Reputation: 2472

To best use IEnumerable interface. Otherwise you can use linq queries for that or basic foreach loop

Upvotes: 0

Igal Tabachnik
Igal Tabachnik

Reputation: 31548

How about simply:

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

No Linq needed, and if you need an array, call ToArray().

Upvotes: 6

Tarik
Tarik

Reputation: 81711

I assume that you want something like this :

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

   returns Name;
}

Upvotes: 0

Charlie
Charlie

Reputation: 10307

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

Upvotes: 0

pero
pero

Reputation: 4259

 return (from Tag in MyTagArray select Tag.Name).ToArray();

Upvotes: 0

Marcin Deptuła
Marcin Deptuła

Reputation: 11957

var names = from t in tags
            select t.Name;

Something like this will give you an IEnumerable over names, just use .ToArray() if you wan't array of those.

Upvotes: 5

Related Questions