2

I have the following two arrays

var employeeIds = new [] {1, 2, 3, 4};

var employeeNames = new [] {"Sarah", "Connor", "Julia", "Igor" };

I need to Zip them so I can combine the above to array such that the employeeId at index n is combined with employeeName at index n. So I can get anonymous objects like the following

combinedArrays.Select(items => new {Id = items.Item0, Name = items.Item1 });

How do I do that in Linq? If I could get Index in Linq, that would've done it but IEnumerable is not an ordered collection so there is no indexes.

1 Answer 1

6

You mentioned Zip - why not use that?

employeeNames.Zip(employeeIds, (name, id) => new { Id = id, Name = name });

MSDN for Enumerable.Zip: https://msdn.microsoft.com/library/dd267698(v=vs.100).aspx

Also, because you mentioned it you can access the index with the Select method if needed:

var employeeNames = new [] {"Sarah", "Connor", "Julia", "Igor" };
var indices = employeeNames.Select( (name, index) => index );
Sign up to request clarification or add additional context in comments.

3 Comments

Damnit, there is a Zip in Linq to Enumerables?
@fahadash there sure is
@fahadash also because you mentioned it you can access the index with Select if needed. i edited my answer to show

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.