Reputation: 73
I have this class:
public class Person
{
public String name;
public int score;
public float multiplier;
public Person(String nameID)
{
name = nameID;
score = 0;
multiplier = 1.0f;
}
}
And I have a List containing these classes:
private List<Person> _people;
Is there some way I could get a score using a name, like this?
_people.GetScore("example name"); // return the score of the class containing that name?
Upvotes: 1
Views: 118
Reputation: 39946
Use LINQ:
_people.FirstOrDefault(c => c.name == "example name")?.score;
Just don't forget to add using System.Linq;
to your using
directives first. Also note that you need to use Null-conditional operator(?.
) also, that is used to test for null before performing a member access (score
in this case)
Also it would be better to use properties instead of fields:
public string Name { get; set; }
Upvotes: 8
Reputation: 16059
You can use linq query to get the result:
int result = _people.FirstOrDefault(p => p.name == "example name").score
If _people list contains multiple records with name "example name" then you can use where clause and get all results from the list
var results = _people.Where(p => p.name == "example name");
foreach(var r in results)
Console.WriteLine(r.score);
Now you can iterate through the results to get all scores
Here is the implementation: DotNetFiddler
Upvotes: 2
Reputation: 5773
You can you Single
method of IEnumerable
var score = _people.Single(p => p.name == "example name").score
Upvotes: -1