Come faccio a formare un buon delegato predicato per trovare () qualcosa nella mia lista < T > ;?

StackOverflow https://stackoverflow.com/questions/242012

Domanda

Dopo aver esaminato MSDN, non mi è ancora chiaro come dovrei formare un predicato adeguato per utilizzare il metodo Find () in Elenco usando una variabile membro di T (dove T è una classe)

Ad esempio:

public class Car
{
   public string Make;
   public string Model;
   public int Year;
}

{  // somewhere in my code
   List<Car> carList = new List<Car>();
   // ... code to add Cars ...

   Car myCar = new Car();

   // Find the first of each car made between 1980 and 2000
   for (int x = 1980; x < 2000; x++)
   {
       myCar = carList.Find(byYear(x));
       Console.Writeline(myCar.Make + myCar.Model);
   }
}

Cosa dovrebbe essere il mio " byYear " aspetto del predicato?

(L'esempio MSDN parla solo di un Elenco di dinosauri e cerca solo un valore immutabile "saurus" - Non mostra come passare un valore nel predicato ...)

EDIT: sto usando VS2005 / .NET2.0, quindi non credo che la notazione Lambda sia disponibile per me ...

EDIT2: rimosso "1999" nell'esempio perché potrei voler " Trova " programmaticamente basato su valori diversi. L'esempio è stato modificato nella gamma di automobili dal 1980 al 2000 utilizzando il ciclo for-do.

È stato utile?

Soluzione

Ok, in .NET 2.0 puoi usare i delegati, in questo modo:

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);
}

Altri suggerimenti

Puoi usare un'espressione lambda come segue:

myCar = carList.Find(car => car.Year == 1999);

Oppure puoi usare un delegato anonimo:

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);
}

Dato che non puoi usare lambda, puoi semplicemente sostituirlo con un delegato anonimo.

myCar = carList.Find(delegate(Car car) { return car.Year == i; });

Hmm. Pensandoci di più, potresti usare il curry per restituire un predicato.

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

Ora puoi passare il risultato di questa funzione (che è un predicato) al tuo metodo Find:

my99Car = cars.Find(byYear(1999));
my65Car = cars.Find(byYear(1965));

Puoi usare anche questo:

var existData =
    cars.Find(
     c => c.Year== 1999);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top