简体   繁体   中英

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

I want to add one by one values but in for loop how can I iterate through one by one values and add it inside dictionary.

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

I want to add { Name = "test1", Id = 111} when i=0 and want to add { Name = "test2", Id = 222} when i=1 n so on..

Right now i'm adding full collection in every key.(want to achieve this using foreach or 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) });
   }
}

If the count is need and the IEnumerable is to be maintained, then you can try this:

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

New version

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

By the way, dictionary is a bad name for some variable.

I'm done using

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

So you want to a an item from the collection to the dictionary in the for loop? If you cast your IEnumerable to a list or an array, you can easily access it via the index. For example like this: Edit: Code at first created a list every time it looped, which should of course be avoided.

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

I'm not 100% if that is what you need, though. More details to your question would be great.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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