Modify List<string> to convert contents to hyperlinks

浪子不回头ぞ 提交于 2019-12-12 01:56:34

问题


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();


来源:https://stackoverflow.com/questions/41288094/modify-liststring-to-convert-contents-to-hyperlinks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!