I need to create a collection of objects using the contents of an array of Guids and a collection of strings. It's easy enough to do using nested loops such as
Guid[] guids;
string[] names;
NewObject[] combined;
foreach(Guid g in guids) {
foreach(string name in names) {
combined.Add(new NewObject() {
Guid = g, Name = name
}
}
}
What I'm wondering is if there's a way that I could do this without the nested loop. I've been wracking my brain to try to figure out a way, but can't come up with one.
CodePudding user response:
Try with Enumerable.Zip:
Guid[] guids;
string[] names;
NewObject[] combined;
var combinedObjects = Enumerable.Zip<Guid, string, NewObject>(guids, names, (guid, name) => new NewObject {Guid = guid, Name = name});
CodePudding user response:
First of all, arrays should be of the same size. and then you can run a single for
loop to set the object, there is no need for two for
loops.
NewObject[] combined = new NewObject[guids.Length];
for (int i = 0; i < guids.Length; i )
{
combined[i] = new NewObject { Guid = guids[i], Name = names[i] };
}