1

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?
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
James A
  • 73
  • 11

3 Answers3

8

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; }
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
2

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

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
-1

You can you Single method of IEnumerable

var score = _people.Single(p => p.name == "example name").score
ema
  • 5,668
  • 1
  • 25
  • 31