다른 컬렉션에있는 경우 개체 목록의 모든 중복 항목을 업데이트하려고합니다.
이것은 내가 가진 코드입니다.
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] 삭제
몇 마디 만하겠습니다