Reputation: 9928
I have two objects
List<string> ids;
List<string> names;
Both have same lentgh/size.
I want to display them as hyperlinks in a foreach loop. I have tried to control the index of names list using an integer iteration on each step.
int i = 0;
foreach (string id in ids)
{
body.InnerHtml += "<h2><a href='go.aspx?id=" + id + "'>"+ names[i++] +"</a></h2>";
}
This works well, but is there any better way?
Upvotes: 0
Views: 5734
Reputation: 5536
An alternate approach is to use a for loop with a total count. E.g.:
int totalCount = listOfStringsA.Count + listOfStringsB.Count;
for (int count=0; count < totalCount; count++)
{
string item = null;
if (count < totalCount) item = listOfStringsA[count];
else item = listOfStringsB[count - totalCount];
// do whatever with item ...
}
Upvotes: 0
Reputation: 73492
Use Enumerable.Zip. That's what it's meant for.
foreach (var item in ids.Zip(names, (id, name) => new { id, name }))
{
body.InnerHtml += "<h2><a href='go.aspx?id=" + item.id + "'>" + item.name + "</a></h2>";
}
Also I recommend StringBuilder for string concatenation in the loop.
If you need to access some fields together, they should probably be located together. I mean create a new class and store them together.
class MyItem
{
public string Id {get; set;}
public string Name {get; set;}
}
Then use List<MyItem>
. If you were doing this, you shouldn't have had this question in first place :)
Upvotes: 4
Reputation: 46967
One possibly solution is to use Linq's Zip function:
const string link = "<h2><a href='go.aspx?id={0}'>{1}</a></h2>";
body.InnerHtml += String.Concat(
ids.Zip(names, (id, name) => String.Format(link, id, name)));
Upvotes: 2
Reputation: 4409
If you really want to use a foreach
loop, make a new collection with LINQ (Zip extension method) and iterate over that:
var combined = ids.Zip(names, (id, name) => new { id = id, name = name });
foreach(var c in combined)
{
body.InnerHtml += "<h2><a href='go.aspx?id=" + c.id + "'>"+ c.name +"</a></h2>"
}
Upvotes: 3
Reputation: 12324
Why not use a for
loop?
for (int i = 0; i < ids.Count; i++)
{
body.InnerHtml += "<h2><a href='go.aspx?id=" + ids[i] + "'>"+ names[i] +"</a></h2>"
}
Upvotes: -1