0

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?

4

2 回答 2

3

我建议验证 FirstOrDefault() 的返回值如下:

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

该错误可能与您认为的不完全一样。

于 2013-11-12T03:28:09.327 回答
-2

试试这个代码。

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

您最好在分配之前检查 Object Null。

于 2013-11-12T03:10:49.453 回答