簡體   English   中英

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

[英]How to iterate through IEnumerable collection using for each or foreach?

我想逐個添加值但是在for循環中如何迭代逐個值並將其添加到字典中。

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

我想在i=0時添加{ Name = "test1", Id = 111}並且當i=1 n時想要添加{ Name = "test2", Id = 222}等等。

現在我正在每個鍵中添加完整的集合。(希望使用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) });
   }
}

如果需要計數並且要維護IEnumerable,那么您可以嘗試這樣做:

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

新版本

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

那么你想要一個從集合中的項目到for循環中的字典? 如果將IEnumerable轉換為列表或數組,則可以通過索引輕松訪問它。 例如:編輯:代碼首先在每次循環時創建一個列表,當然應該避免。

var list = collection.ToList(); //ToArray() also possible
for (int i = 0; i < list.Count(); i++)
{ 
  dictionary.Add(i, list[i]);
}

不過,如果你需要的話,我不是百分之百。 你問題的更多細節會很棒。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM