다른 목록에있는 경우 List <Objects>에서 모든 중복 항목을 업데이트하는 방법은 무엇입니까?

아 포스트로 픽스

다른 컬렉션에있는 경우 개체 목록의 모든 중복 항목을 업데이트하려고합니다.

이것은 내가 가진 코드입니다.

public class Cars
{
    public string brand { get; set; }
    public string model { get; set; }
    public string allowed { get; set; }
}

var notAllowedModels = GetNotAllowedModels(); // returns a List<String> with model names

foreach(var car in cars) // cars is a List<Car>
{
    if (notAllowedModels.Contains(car.model))
       cars[cars.FindIndex(x => x.model == car.model)].allowed = "No";
    else
       cars[cars.FindIndex(x => x.model == car.model)].allowed = "Yes";
}

목록의 모델이 고유 한 경우 제대로 작동하지만 두 번 이상 존재하면 첫 번째 모델 만 업데이트되고 다른 모델은 null이됩니다.

아무도 notAllowedModels목록 에있는 경우 모든 중복 항목을 업데이트하는 방법을 생각할 수 있습니까 ?

FindAll대신 사용할 수 있다는 것을 알고 FindIndex있지만 목록을 반환하고 중복 항목과 동일한 문제가 될 것이기 때문에 정확히 어떻게 도움이되는지 확실하지 않습니다.

팀 슈멜 터

List.FindIndex차를 찾기 위해 사용할 필요가 없습니다 . 이미 가지고 있습니다.

foreach(Car car in cars) // cars is a List<Car>
{
    if (notAllowedModels.Contains(car.model))
       car.allowed = "No";
    else
       car.allowed = "Yes";
}

성능을 향상하려면 방법에 의해,를 반환 HashSet<string>에서 GetNotAllowedModels. 고유 한 값만 포함하고 조회 ( Contains) 에서 매우 효율적입니다 .

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관