Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two enumerables: IEnumerable<A> list1 and IEnumerable<B> list2. I would like to iterate through them simultaneously like:

foreach((a, b) in (list1, list2))
{
    // use a and b
}

If they don't contain the same number of elements, an exception should be thrown.

What is the best way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
327 views
Welcome To Ask or Share your Answers For Others

1 Answer

You want something like the Zip LINQ operator - but the version in .NET 4 always just truncates when either sequence finishes.

The MoreLINQ implementation has an EquiZip method which will throw an InvalidOperationException instead.

var zipped = list1.EquiZip(list2, (a, b) => new { a, b });

foreach (var element in zipped)
{
    // use element.a and element.b
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...