我正在尝试运行此代码,但a
始终为null
。我确定有一个Name
,为什么它总是返回null?
public Animal FindAnimal(string Name)
{
Animal a = Animals.Find(
delegate(Animal bk)
{
return bk.AnimalName.ToLower() == Name.ToLower();
}
);
return a;
}
答案 0 :(得分:1)
您的代码对我来说很好。以下是一些小优化:
public Animal FindAnimal(string name)
{
return Animals.Find((a) => String.Equals(a.AnimalName, name, StringComparison.CurrentCultureIgnoreCase));
}
修改强> 代码测试:
void Main()
{
var foundAnimal = FindAnimal("Monkey"); //Not null
}
List<Animal> Animals = new List<Animal>(){ new Animal() { AnimalName = "Monkey" }};
public Animal FindAnimal(string name)
{
return Animals.Find((a) => String.Equals(a.AnimalName, name, StringComparison.CurrentCultureIgnoreCase));
}
public class Animal
{
public string AnimalName { get; set; }
}