list.find问题

时间:2011-05-29 20:08:51

标签: c#

我正在尝试运行此代码,但a始终为null。我确定有一个Name,为什么它总是返回null?

   public  Animal FindAnimal(string Name)
    {
        Animal a = Animals.Find(

            delegate(Animal bk)
            {
                return bk.AnimalName.ToLower() == Name.ToLower();
            }


            );
        return a;

    }

1 个答案:

答案 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; }
}