3

Here are my C# classes:

public class myClass {

     // Some properties irrelevant to the question

     public List<someObject> ListOfStuff { get; set; }
}


public class someObject {

   public string Id { get; set; }

   public string Name { get; set; }
}

Question: is it possible to extract all Id into a separate array and all Name into another separate array?

For instance, something like this:

 myClass foo;
 // Populate foo...  
 List<string> names = foo.ListOfStuff( what goes here? );

4 Answers 4

5

You can do it using the Select method of LINQ:

List<string> names = foo.ListOfStuff.Select(x => x.Name).ToList<string>();
List<string> ids = foo.ListOfStuff.Select(x => x.Id).ToList<string>();
Sign up to request clarification or add additional context in comments.

3 Comments

@Hasanain: Right, just added it.
Might want to add that you need to include using System.Linq; to use LINQ.
@norlando: Well, it is written in the tree on the left of the documentation page of the method. If we had to write the required using on every SO answer, I just think that would pollute the answers.
3

LINQ makes this quite easy:

var idArray = ListOfStuff.Select(item => item.Id).ToArray();

To get your array of Names, just change the property you're selecting in the Select() method.

Comments

2

You can use LINQ to accomplish this, e.g.

List<string> names = foo.ListOfStuff.Select(x => x.Name).ToList();

Comments

2

Here are the linq queries to accomplish what you're looking to do:

IEnumerable<string> names = foo.ListOfStuff.Select(f => f.Name);
IEnumerable<string> IDs = foo.ListOfStuff.Select(f => f.Id);

If you want to store them in a List, then just tack a ToList() onto the end of those queries:

List<string> IDs = foo.ListOfStuff.Select(f => f.Id).ToList();
List<string> Names = foo.ListOfStuff.Select(f => f.Name).ToList();

1 Comment

The "Id" property is a string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.