C# 如何使用for each或foreach遍历IEnumerable集合?

C# 如何使用for each或foreach遍历IEnumerable集合?,c#,dictionary,ienumerable,ienumerator,C#,Dictionary,Ienumerable,Ienumerator,我想逐个添加值,但在for循环中如何迭代 通过一个接一个的值并将其添加到字典中 IEnumerable<Customer> items = new Customer[] { new Customer { Name = "test1", Id = 111}, new Customer { Name = "test2", Id = 222} }; 如果需要计数并且要维护IEnumerable,则可以尝试以下方法: int count = 0; var enu

我想逐个添加值,但在for循环中如何迭代 通过一个接一个的值并将其添加到字典中

IEnumerable<Customer> items = new Customer[] 
{ 
     new Customer { Name = "test1", Id = 111}, 
     new Customer { Name = "test2", Id = 222} 
};

如果需要计数并且要维护IEnumerable,则可以尝试以下方法:

int count = 0;
var enumeratedCollection = collection.GetEnumerator();
while(enumeratedCollection.MoveNext())
{
 count++;
 await dictionary.Set(new[] { new KeyValuePair<object,T>( count,enumeratedCollection.Current) });
}
int count=0;
var enumeratedCollection=collection.GetEnumerator();
while(enumeratedCollection.MoveNext())
{
计数++;
wait dictionary.Set(new[]{newkeyvaluepair(count,enumeratedCollection.Current)});
}

那么您想在for循环中将一个项从集合添加到字典? 如果将
IEnumerable
强制转换为列表或数组,则可以通过索引轻松访问它。例如: 编辑:代码在每次循环时首先创建一个列表,这当然应该避免

var list = collection.ToList(); //ToArray() also possible
for (int i = 0; i < list.Count(); i++)
{ 
  dictionary.Add(i, list[i]);
}
var list=collection.ToList()//ToArray()也是可能的
对于(int i=0;i
不过,如果这是你需要的,我不是100%。您的问题的更多细节将非常有用。

新版本

var dictionary = items.Zip(Enumerable.Range(1, int.MaxValue - 1), (o, i) => new { Index = i, Customer = (object)o });
顺便说一句,字典对某些变量来说是个坏名字。

我已经不用字典了

string propertyName = "Id";
    Type type = typeof(T);
                var prop = type.GetProperty(propertyName);
                foreach (var item in collection)
                {
                    await dictionary.Set(new[] { new KeyValuePair<object, T>(prop.GetValue(item, null),item) });
                }
string propertyName=“Id”;
类型=类型(T);
var prop=type.GetProperty(propertyName);
foreach(集合中的var项)
{
wait dictionary.Set(new[]{newkeyvaluepair(prop.GetValue(item,null),item)});
}

现在不在计算机上,但我可以想象你可以这样处理它:foreach(字典中的KeyValuePair项){//Do stuff with item.Key和item.Value}如果不是,编译器会告诉你并打错电话给我。参数“string Key”是什么意思?@knagaev很抱歉更新了混淆。为什么你的密钥是对象而不是in?你到底在用字典做什么?:)你的foreach循环中的
i
来自哪里?;)这太糟糕了。你每次都在创建一个列表,我甚至不知道我是否答对了他的问题,我只是草草写下一点代码来告诉他怎么做。不过我会编辑它,因为你当然是对的,不应该在每次迭代中都创建一个列表?具有IEnumerable中的索引键和对象值的字典?
string propertyName = "Id";
    Type type = typeof(T);
                var prop = type.GetProperty(propertyName);
                foreach (var item in collection)
                {
                    await dictionary.Set(new[] { new KeyValuePair<object, T>(prop.GetValue(item, null),item) });
                }