如何使用for each或foreach迭代IEnumerable集合?

时间:2015-08-24 06:50:34

标签: c# dictionary ienumerable ienumerator

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

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

我想在{ Name = "test1", Id = 111}时添加i=0 并希望在{ Name = "test2", Id = 222} n时添加i=1 ..

现在我正在每个键中添加完整的集合。(希望使用foreach或forloop实现此目的)

public async void Set(IEnumerable collection)
{
   RedisDictionary<object,IEnumerable <T>> dictionary = new RedisDictionary>(Settings, typeof(T).Name);
// Add collection to dictionary;
   for (int i = 0; i < collection.Count(); i++)
   { 
     await dictionary.Set(new[] { new KeyValuePair<object,IEnumerable <T>  ( i ,collection) });
   }
}

4 个答案:

答案 0 :(得分:2)

如果需要计数并且要维护IEnumerable,那么你可以试试这个:

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

答案 1 :(得分:1)

新版

var dictionary = items.Zip(Enumerable.Range(1, int.MaxValue - 1), (o, i) => new { Index = i, Customer = (object)o });

顺便说一句,字典对于某些变量来说是一个坏名字。

答案 2 :(得分:0)

我已经完成了

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

答案 3 :(得分:-2)

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

var list = collection.ToList(); //ToArray() also possible
for (int i = 0; i < list.Count(); i++)
{ 
  dictionary.Add(i, list[i]);
}
但是,如果这是你所需要的,我不是100%。你问题的更多细节会很棒。

相关问题