Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Equivalent of Python's itertools.chain

Tags:

c#

What (if any) is the C# equivalent of Python's itertools.chain method?

Python Example:

l1 = [1, 2]
l2 = [3, 4]
for v in itertools.chain(l1, l2):
    print(v)

Results:
1
2
3
4

Note that I'm not interested in making a new list that combines my first two and then processing that. I want the memory/time savings that itertools.chain provides by not instantiating this combined list.

like image 805
user12861 Avatar asked Mar 27 '12 17:03

user12861


2 Answers

You could do the same on C# by using the Concat extension method from LINQ:

l1.Concat(l2)

LINQ uses a deferred execution model, so this won't create a new list.

like image 192
Botz3000 Avatar answered Sep 30 '22 01:09

Botz3000


Enumerable.Concat (MSDN)

var l1 = new List<int>() { 1, 2 }; 
var l2 = new List<int>() { 3, 4 }; 

foreach(var item in Enumerable.Concat(l1, l2))
{
    Console.WriteLine(item.ToString()) 
}
like image 33
Phil Price Avatar answered Sep 30 '22 01:09

Phil Price