Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pairing Collections in Linq without a For Loop

Tags:

c#

linq

I have two collections

int[] numbers = {5, 2, 1, 5};
string[] words = {"flibble", "bobble", "double", "dumble"};

I want to use a linq expression on the second collection using the first. Using a loop I'd do the following

List<string> results = new List<string>();
for(int i = 0; i<numbers.Count(), i++)
{
  results.Add(words[i].SubString(numbers[i]);
}
return results;

However this involves creating a list for no real reason... is there a way to do this in Linq?

like image 513
Liath Avatar asked Dec 07 '25 10:12

Liath


1 Answers

I'm guessing you're looking for Enumerable.Zip():

numbers.Zip(words, (n, w) => w.Substring(n));
like image 66
Justin Niessner Avatar answered Dec 09 '25 23:12

Justin Niessner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!