问题
I am using following snippet to some items to a list of strings. But it is throwing an exception.
List<string> guids = null;
QueryExpression qExp = new QueryExpression
{
EntityName = "account",
ColumnSet = col1,
Criteria = new FilterExpression
{
Conditions = {
new ConditionExpression("statecode",ConditionOperator.Equal,0)
}
}
};
sp.CallerId = g1;
EntityCollection ec1 = sp.RetrieveMultiple(qExp);
foreach (Entity item in ec1.Entities)
{
guids.Add(Convert.ToString(item.Attributes["accountid"]));
}
Exception: Object reference not set to an instance of an object
回答1:
Why not use LINQ:
List<string> guids = ec1.Entities
.Select(entity => Convert.ToString(entity.Attributes["accountid"]))
.ToList();
回答2:
Change List<string> guids = null; to List<string> guids = new List<string>(); and all will be well.
You must initialise the list before you can start writing to it. You are setting it to null, thus the exception.
回答3:
You cannot use List<string> guids = null;
Try to do List<string> guids = new List<string>();
来源:https://stackoverflow.com/questions/34204676/how-add-items-to-a-list-in-foreach-loop-using-c-sharp