Alex Rivera | Logout

List<T>.ForEach with index

Asked 2012-10-24T17:14:08.343
35

I'm trying to find the LINQ equivalent of the following code:

NameValueCollection nvc = new NameValueCollection();

List<BusinessLogic.Donation> donations = new List<BusinessLogic.Donation>();
donations.Add(new BusinessLogic.Donation(0, "", "", "");
donations.Add(new BusinessLogic.Donation(0, "", "", "");
donations.Add(new BusinessLogic.Donation(0, "", "", "");

for(var i = 0; i < donations.Count(); i++)
{
    // NOTE: item_number_ + i - I need to be able to do this
    nvc.Add("item_number_" + i, donations[i].AccountName);
}

I was hoping I could use something like:

NameValueCollection nvc = new NameValueCollection();

List<BusinessLogic.Donation> donations = new List<BusinessLogic.Donation>();
donations.Add(new BusinessLogic.Donation(0, "", "", "");
donations.Add(new BusinessLogic.Donation(0, "", "", "");
donations.Add(new BusinessLogic.Donation(0, "", "", "");

donations.ForEach(x => nvc.Add("item_name_" + ??, x.AccountName);

But I've not found a way to determine which iteration the loop is on. Any help would be appreciated!

Edit
Report

1 Answer

3

Is there any reason you're not using a Dictionary<string, string> as your names/keys appear to be unique? This would be faster and you could use the ToDictionary standard query operator.

Also, if you did wish to use an extension method (although as Servy says a for loop is the right solution here), then you could write your own - see here.

answered 2012-10-24T17:28:40.450

Your Answer