문제

나는 람다 표현을 좋아하기 시작했지만이 벽을 통과하기 위해 고군분투하고 있습니다.

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

내 검색 :

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

그래서 나는 내가 찾고있는 그 사람 (직원)을 가진 대상을 얻고 싶습니다.'bool'으로 '사람'을 암시 할 수 없음)"어느 것이 맞지만, 내가 사람의 대상을 지나치지 않는다면, 첫 번째 찾기는 어떻게 실행할 수 있습니까?

도움이 되었습니까?

해결책

존재를 확인하고 싶기 때문에 시도해보십시오.

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

이것은 어떤지 확인합니다 Person 동일하게 ParID; 당신이 똑같이 의미한다면 Person 그렇다면 인스턴스 (참조) Contains 충분해야합니다 :

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

다른 팁

Find() 발견 된 개체를 반환합니다. 사용 Any() 모든 요소에 대해 표현식이 참인지 확인하십시오.

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 보고 단 하나 물체, x.Employees.Find(..) 보고 Person.

.Find 부울 매개 변수를 기대합니다 (예 : 조건의 결과). 그래서 컴파일러 오류가있는 이유입니다. Cannot implicit convert 'Person' To 'bool'

.Where 따라서 여러 개체를 반환 할 수 있습니다 모든 것을 반복 할 수 있습니다 목록.

조합을 사용하십시오 .Where 그리고 .Any 당신의 경우.

다음 코드는 차이점을 설명합니다 .Where, .Find, 그리고 .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; }
}

그것은 당신이 당신의 최상위 찾기에 대한 합법적 인 찾기 표현을 지정하지 않았기 때문입니다.

여기에 보여 드리겠습니다.

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

그렇다면 초기 찾기 조건은 무엇입니까?

가장 쉬운 것은입니다

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

무효 점검없이

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top