leora
leora

Reputation: 196469

best way to compare items inside a loop

i have a collection of objects. i need to loop through the collection and generate another collection. each item in the second collection is a function of two items in the first collections. So to simplify the problem.

Lets assume the collection is a set of ints.

 List<int> myIntCollection = new List<int>() {1, 4, 6, 8, 7};

i need to generate a second collection in which each item is the sum of 2 of the items in the first collection. so the second collection would have these elements after the conversion.

 List<int> generatedCollection = new List<int>() {5, 10, 14, 15};

as you can see the first element is 5 (which is the sum of the first two items in the top collection), the second elemtn is 10, which is hte sum of the second and third item in the first collection and so on . .

Upvotes: 0

Views: 216

Answers (3)

Guffa
Guffa

Reputation: 700292

You can use the Enumerable.Range method to create a collection on the fly, and get the sum of two items for each index:

List<int> generatedCollection =
  Enumerable.Range(0, myIntCollection.Length - 1)
  .Select(i => myIntCollection[i] + myIntCollection[i + 1])
  .ToList();

Upvotes: 0

sarvesh
sarvesh

Reputation: 2743

int i = 0;
generatedCollection.AddRange(
            myIntCollection.Where(j => i < myIntCollection.Count - 1).Select(
                j => myIntCollection[i] + myIntCollection[i++ + 1]));

Upvotes: 0

SLaks
SLaks

Reputation: 887385

You can use a for loop:

List<int> result = new List<int>(source.Count - 1);

for (int i = 0; i < source.Count - 1; i++)
    result.Add(source[i] + source[i + 1]);

That wasn't hard!

Upvotes: 6

Related Questions