tags:

views:

129

answers:

6

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

A: 

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

Cihan Yakar
+4  A: 
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.

Ravadre
or simply tags.Select(t => t.Name);
Rune FS
A: 
 return (from Tag in MyTagArray select Tag.Name).ToArray();
Petar Repac
A: 
string[] tagArray = (from t in tagList select t.Name).ToArray();
Charlie
A: 

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;
}
Braveyard
Why not use linq? You can do this in one line of code.
Charlie
he said "as an array of strings"
Petar Repac
@Charlie : Everyone wrote the code in LINQ, I wanted show something different.
Braveyard
@Aaron fair enough, good for C#2. You should edit your answer to return an array of strings rather than a list like the question says though.
Charlie
+5  A: 

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().

hmemcpy
+1 Nicest solution :)
Charlie