如何使用C#在foreach循环中将项目添加到列表 [英] How add items to a list in foreach loop using c#
本文介绍了如何使用C#在foreach循环中将项目添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码片段到字符串列表中的某些项目.但这引发了异常.
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
推荐答案
为什么不使用LINQ:
Why not use LINQ:
List<string> guids = ec1.Entities
.Select(entity => Convert.ToString(entity.Attributes["accountid"]))
.ToList();
这篇关于如何使用C#在foreach循环中将项目添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文