zkanoca
zkanoca

Reputation: 9928

How to combine two lists in a single foreach loop in C# ASP.NET?

I have two objects

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

Answers (5)

Aidan
Aidan

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

Sriram Sakthivel
Sriram Sakthivel

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

Magnus
Magnus

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

thekaveman
thekaveman

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

Vsevolod Goloviznin
Vsevolod Goloviznin

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

Related Questions