Domanda

Sto iniziando ad amare le espressioni Lambda ma sto lottando per superare questo muro:

public class CompanyWithEmployees {
    public CompanyWithEmployees() { }
    public Company CompanyInfo { get; set; }
    public List<Person> Employees { get; set; }
}

La mia ricerca:

List<CompanyWithEmployees> companiesWithEmployees = ws.GetCompaniesWithEmployees();
CompanyWithEmployees ces = companiesWithEmployees
        .Find(x => x.Employees
        .Find(y => y.PersonID == person.PersonID));

Quindi, voglio ottenere l'oggetto " CompanyWithEmployees " quella persona (Dipendente) che sto cercando, ma sto ottenendo " Impossibile convertire implicitamente "Persona" in "bool") " che è corretto, ma se non passo l'oggetto Person, come può essere eseguito il primo Find?

È stato utile?

Soluzione

Perché vuoi verificare l'esistenza, forse prova:

ces = companiesWithEmployees
        .Find(x => x.Employees
        .Find(y => y.ParID == person.ParID) != null);

Questo controllerà qualsiasi Persona con lo stesso ParID ; se intendi la stessa istanza Person (riferimento), Contains dovrebbe essere sufficiente:

ces = companiesWithEmployees
        .Find(x => x.Employees.Contains(person));

Altri suggerimenti

Trova () restituisce l'oggetto trovato. Usa Any () per verificare se l'espressione è vera per qualsiasi elemento.

var ces = companiesWithEmployees
    .Find(x => x.Employees
    .Any(y => y.PersonID == person.PersonID));
ces = companiesWithEmployees
    .First(x => x.Employees.Any(p=>p.PersonID == person.PersonID));
ces = companiesWithEmployees.Find( x => x.Employees.Find(...) );

.Find restituisce solo un oggetto , x.Employees.Find (..) restituisce persona .

.Find si aspetta un parametro booleano (cioè il risultato di condizioni), ecco perché c'è un errore del compilatore che dice Impossibile convertire implicitamente 'Person' in 'bool'

.Where può restituire più oggetti, quindi può scorrere in tutto l'elenco .

usa una combinazione di .Where e .Any nel tuo caso.

il seguente codice illustrerà la differenza tra .Where , .Find e .Any :

public partial class Form2 : Form {
    public Form2() {
        InitializeComponent();
        var companiesWithEmployees = new List<CompanyWithEmployees>() {                
            new CompanyWithEmployees {                 
                CompanyInfo = new Company { CompanyName = "Buen" },
                Employees = new List<Person>()  { 
                    new Person { PersonID = 1976, PersonName = "Michael" },
                    new Person { PersonID = 1982, PersonName = "Mark" },
                    new Person { PersonID = 1985, PersonName = "Matthew" },                            
                    new Person { PersonID = 1988, PersonName = "Morris" }
                }
            },
            new CompanyWithEmployees {
                CompanyInfo = new Company { CompanyName = "Muhlach" },
                Employees = new List<Person>() {
                    new Person { PersonID = 1969, PersonName = "Aga" },
                    new Person { PersonID = 1971, PersonName = "Nino" },
                    new Person { PersonID = 1996, PersonName = "Mark" }
                }
            },
            new CompanyWithEmployees {
                CompanyInfo = new Company { CompanyName = "Eigenmann" },
                Employees = new List<Person>() {
                    new Person { PersonID = 1956, PersonName = "Michael" },                        
                    new Person { PersonID = 1999, PersonName = "Gabby" }
                }
            }
        };

        // just explicitly declared the types (instead of var) so the intent is more obvious

        IEnumerable<CompanyWithEmployees> whereAreMichaels = companiesWithEmployees
            .Where(cx => cx.Employees.Any(px => px.PersonName == "Michael"));

        string michaelsCompanies = string.Join(", ", whereAreMichaels
            .Select(cx => cx.CompanyInfo.CompanyName).ToArray());

        MessageBox.Show("Company(s) with employee Michael : " + michaelsCompanies);

        Person findAga = companiesWithEmployees
            .Find(company => company.CompanyInfo.CompanyName == "Muhlach")
            .Employees.Find(person => person.PersonName == "Aga");

        if (findAga != null)
            MessageBox.Show("Aga's ID : " + findAga.PersonID.ToString());
    }
}

class CompanyWithEmployees { 
    public Company CompanyInfo { get; set; }
    public List<Person> Employees { get; set; }
}
class Company {
    public string CompanyName { get; set; }
}
class Person {
    public int PersonID { get; set; }
    public string PersonName { get; set; }
}

Questo perché non hai specificato un'espressione Trova legittima per la ricerca di livello superiore.

Lo mostrerò qui:

ces = companiesWithEmployees
    .Find (x => x.Employees.Find(y => y.ParID == Person.ParID) /*condition is missing here*/);

Quindi qual è la condizione per la tua ricerca iniziale?

Il più semplice sarebbe

ces = companiesWithEmployees.FirstOrDefault(x => 
          x.Employees.Any(y => y.PersonID == person.ParID));

senza alcun controllo null

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top