简体   繁体   English

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

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

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 例外:对象引用未设置为对象的实例

Change List<string> guids = null; 更改List<string> guids = null; to List<string> guids = new List<string>(); 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. 您将其设置为null ,因此是例外。

Why not use LINQ: 为什么不使用LINQ:

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

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

Try to do List<string> guids = new List<string>(); 尝试做List<string> guids = new List<string>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM