How add items to a list in foreach loop using c#

岁酱吖の 提交于 2019-12-11 10:29:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!