Modify List to convert contents to hyperli

2019-09-06 09:44发布

问题:

I have a List<string> that get's populated with URLs. What I'd like to do is convert the contents of the List to hyperlinks that the user can click on. I've seen a bunch of examples of how to do this, but most of them were to insert in to an email, or switch the word here to a hyperlink. I just don't know what I'm looking at, so it's a little confusing. Here's what I have:

List<string> lstUrls = new List<string>();
//PROGRAM GETS URLS FROM ELEMENTS IN HERE....
foreach (string s in lstUrls)
{
    s = "<a href=\"%s\"></a>";    //THIS DOESN'T WORK...
}  

I don't want to change the content of the string - just to be able to display as a hyperlink. For example, one string value will be https://www.tyco-fire.com/TD_TFP/TFP/TFP172_02_2014.pdf; and how Stack Overflow displays it as a link, that's what I would like to accomplish.

I know I'm obviously botching the syntax. Any help is appreciated.

回答1:

You can´t change the content of a List<T> while iterating it using foreach. But you can using for:

for(int i = 0; i < lstUrls.Count; i++)
{
    var s = lstUrls[i];
    lstUrls[i] = "<a href=\"" + s + "\">" + s + "</a>";
}

A bit easier to read was this:

lstUrls[i] = String.Format("<a href=\"{0}\">{0}</a>", s);


回答2:

You could use linq for it:

lstUrls = lstUrls.Select(s => $"<a href=\"{s}\"></a>").ToList();

Or rather displaying the url in it:

lstUrls = lstUrls.Select(s => $"<a href=\"{s}\">{s}</a>").ToList();