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

前端 未结 6 1487
囚心锁ツ
囚心锁ツ 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 12:43

    Since you can't use lambda you can just replace it with an anonymous delegate.

    myCar = carList.Find(delegate(Car car) { return car.Year == i; });
    
    0 讨论(0)
  • 2020-12-23 12:48

    You can use a lambda expression as follows:

    myCar = carList.Find(car => car.Year == 1999);
    
    0 讨论(0)
  • 2020-12-23 12:49

    Hmm. Thinking more about it, you could use currying to return a predicate.

    Func<int, Predicate<Car>> byYear = i => (c => c.Year == i);
    

    Now you can pass the result of this function (which is a predicate) to your Find method:

    my99Car = cars.Find(byYear(1999));
    my65Car = cars.Find(byYear(1965));
    
    0 讨论(0)
  • 2020-12-23 13:02

    Or you can use an anonymous delegate:

    Car myCar = cars.Find(delegate(Car c) { return c.Year == x; });
    
    // If not found myCar will be null
    if (myCar != null)
    {
         Console.Writeline(myCar.Make + myCar.Model);
    }
    
    0 讨论(0)
  • 2020-12-23 13:02

    You can use this too:

    var existData =
        cars.Find(
         c => c.Year== 1999);
    
    0 讨论(0)
  • 2020-12-23 13:07

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

    static Predicate<Car> 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<Car> list = new List<Car>
        {
            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);
    }
    
    0 讨论(0)
提交回复
热议问题