Eknoes
Eknoes

Reputation: 359

Get data from a list in C#

I've created a list of a class. Here you can see the code:

public class People{
        public string name;
        public int age;     
    }   

public List<People> peopleInfo = new List<People>();

My problem is that I have for example a name and now I want to know the age. How do I get this data? I can get a name or the age on a specific position by this:

int pos = peopleInfo[0].name;

But how I can do it the inverted way and get the position of name? When I have this it easy to get the age.

Upvotes: 3

Views: 43111

Answers (3)

Alexander
Alexander

Reputation: 4173

You can use FindIndex to find person by name. But in case if this operation will be frequent, you may hit performance problems, as each FindIndex call will look up through entire list, one record by one.

Probably in this situation it would be better to build dictionary of persons by name. Or even dictionary of age by name, if the only thing you need is a person's age.

Also, consider case when person name is not unique.

List<People> peopleInfo = new List<People>() { ... };
Dictionary<string, People> map = peopleInfo.ToDictionary(p => p.name);
People p = map["John"];

Upvotes: 4

p.s.w.g
p.s.w.g

Reputation: 148980

You can use the FindIndex method:

var searchForName = "John";
int index = peopleInfo.FindIndex(p => p.name == searchForName);

This will return the index of the first person in the list whose name property is equal to "John". Of course there may be many people with the name "John", and you may want to find all of them. For this you can use LINQ:

IEnumerable<int> indexes = peopleInfo.Select((p, i) => new { p, i })
                                     .Where(x => x.p.name == searchForName)
                                     .Select(x => x.i);
foreach(int i in indexes)
{
    peopleInfo[i].age ...
}

But if you don't really need the index, this is much more simple:

foreach(People person in peopleInfo.Where(p => p.name == searchForName))
{
    person.age ...
}

Upvotes: 6

John Kraft
John Kraft

Reputation: 6840

int index = peopleInfo.FindIndex(p => p.name == "TheName");

or, you could just find the object directly...

People person = peopleInfo.FirstOrDefault(p => p.name == "TheName");

Upvotes: 1

Related Questions