3

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

1
  • What ? Names of what , Name properties or Tag Instance Identifiers ? Commented Sep 5, 2009 at 9:33

6 Answers 6

6

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

Sign up to request clarification or add additional context in comments.

Comments

5
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.

1 Comment

or simply tags.Select(t => t.Name);
0
 return (from Tag in MyTagArray select Tag.Name).ToArray();

Comments

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

Comments

0

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

3 Comments

he said "as an array of strings"
@Charlie : Everyone wrote the code in LINQ, I wanted show something different.
@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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.