문제

I have a list of objects as ICollection<objectA> listA. Now I'm trying to loop thru this listA and trying to match a condition and assign the result found into a variable. I tried below:

varB.someDesc = listA.FirstOrDefault(x=>x.ID == varB.ID).someDesc

Error complaining that x.ID is object null reference. When I put a break point, I can see there are many items in listA and there is an attribute ID. May I know what goes wrong?

도움이 되었습니까?

해결책

I suggest validating the return value of FirstOrDefault() as follows:

var item = listA.FirstOrDefault(x=>x.ID == varB.ID);
if (item != null)
    varB.someDesc = item.someDesc;

The error might not be exactly what you think it is.

다른 팁

Try this code.

varB.someDesc = listA.Where(x=>x.ID == varB.ID).FirstOrDefault().someDesc

you better check Object Null before assigning.

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