我有这个课:
public class Person
{
public String name;
public int score;
public float multiplier;
public Person(String nameID)
{
name = nameID;
score = 0;
multiplier = 1.0f;
}
}
我有一个包含这些类的列表:
private List<Person> _people;
有什么办法可以像我这样使用名字来获得分数吗?
_people.GetScore("example name"); // return the score of the class containing that name?
最佳答案
使用LINQ:
_people.FirstOrDefault(c => c.name == "example name")?.score;
只是不要忘记先将
using System.Linq;
添加到using
指令中。还要注意,还需要使用Null-conditional运算符(?.
),该运算符用于在执行成员访问之前测试null(在这种情况下为score
)另外,最好使用properties代替字段:
public string Name { get; set; }
关于c# - 在列表中查找具有特定值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48983305/