How do I form a good predicate delegate to Find() something in my List?

前端 未结 6 1528
囚心锁ツ
囚心锁ツ 2020-12-23 12:37

After looking on MSDN, it\'s still unclear to me how I should form a proper predicate to use the Find() method in List using a member variable of T (where T is a class)

6条回答
  •  心在旅途
    2020-12-23 13:07

    Ok, in .NET 2.0 you can use delegates, like so:

    static Predicate ByYear(int year)
    {
        return delegate(Car car)
        {
            return car.Year == year;
        };
    }
    
    static void Main(string[] args)
    {
        // yeah, this bit is C# 3.0, but ignore it - it's just setting up the list.
        List list = new List
        {
            new Car { Year = 1940 },
            new Car { Year = 1965 },
            new Car { Year = 1973 },
            new Car { Year = 1999 }
        };
        var car99 = list.Find(ByYear(1999));
        var car65 = list.Find(ByYear(1965));
    
        Console.WriteLine(car99.Year);
        Console.WriteLine(car65.Year);
    }
    

提交回复
热议问题