这有效,但很慢,
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetNames(string prefixText, int count)
{
XmlDocument xmlArtist = new XmlDocument();
xmlArtist.Load(string.Format(" http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key={0}&limit=100", key));
List<string> topartists = new List<string>();
foreach (XmlNode node in xmlArtist.SelectNodes("lfm/artists/artist"))
{
string a = node.SelectSingleNode("name").InnerText.ToString();
if (a.Contains(prefixText))
{
topartists.Add(a);
}
}
return topartists;
我想把它变成一个 LINQ 查询来加快速度,我有一段时间没有使用 LINQ 并且查看了很多示例,但无法弄清楚为什么这不起作用。
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetNames(string prefixText, int count)
{
List<string> topartists = new List<string>();
XElement element = XElement.Load("http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists&api_key=...&limit=100");
IEnumerable<XElement> artists =
from el in element.Elements("artist")
where el.Element("name").Value.Contains(prefixText)
select el;
foreach (XElement el in artists)
topartists.Add(el.Value);
return topartists;
这是我使用的 XML 的一部分:
<lfm status="ok">
<artists page="1" perPage="100" totalPages="10" total="1000">
<artist>
<name>Coldplay</name>
<playcount>849564</playcount>
<listeners>124389</listeners>
<mbid>cc197bad-dc9c-440d-a5b5-d52ba2e14234</mbid>
<url>http://www.last.fm/music/Coldplay</url>
<streamable>1</streamable>
<image size="small">http://userserve-ak.last.fm/serve/34/214667.png</image>
<image size="medium">http://userserve-ak.last.fm/serve/64/214667.png</image>
<image size="large">http://userserve-ak.last.fm/serve/126/214667.png</image>
<image size="extralarge">http://userserve-ak.last.fm/serve/252/214667.png</image>
<image size="mega">http://userserve-ak.last.fm/serve/_/214667/Coldplay.png</image>
</artist>
<artist>
<name>Radiohead</name>
<playcount>960812</playcount>
<listeners>104849</listeners>
<mbid>a74b1b7f-71a5-4011-9441-d0b5e4122711</mbid>
<url>http://www.last.fm/music/Radiohead</url>
<streamable>1</streamable>
<image size="small">http://userserve-ak.last.fm/serve/34/24688757.png</image>
<image size="medium">http://userserve-ak.last.fm/serve/64/24688757.png</image>
<image size="large">http://userserve-ak.last.fm/serve/126/24688757.png</image>
<image size="extralarge">http://userserve-ak.last.fm/serve/252/24688757.png</image>
<image size="mega">http://userserve-ak.last.fm/serve/_/24688757/Radiohead.png</image>
</artist>
<artist>