如何使用 C# 将项目添加到 foreach 循环中的列表

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

我正在使用以下代码段将某些项目添加到字符串列表中。但它抛出异常。

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"]));
}

异常: 对象引用未设置到对象的实例

List<string> guids = null;改成List<string> guids = new List<string>();就可以了

您必须先初始化列表,然后才能开始写入。您将其设置为 null,因此是例外。

您不能使用List<string> guids = null;

努力做到List<string> guids = new List<string>();

为什么不使用 LINQ:

List<string> guids = ec1.Entities
   .Select(entity => Convert.ToString(entity.Attributes["accountid"]))
   .ToList();