我很抱歉,因为我还在学习Linq和HtmlAgilityPack,但是我试图将标题和链接分配给已经创建的字符串值。换句话说,如何访问这个.ToList()的值?
下面是我的代码:
string imgTitle;
string imgLink;
private void getCaption(string txt)
{
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml("<html><head></head><body>" + txt + "</body></html>");
if (htmlDoc != null)
{
var elements = htmlDoc.DocumentNode.SelectNodes(@"//img[@src]").Select(img => new
{
Link = img.Attributes["src"].Value,
Title = img.Attributes["alt"].Value
}).ToList();
}
imgTitle = elements[0]["Title"]; //I thought i could do this很抱歉提出了一个愚蠢的问题,但是我还没有看到关于Linq和ToList函数如何工作的很好的解释。当我打印元素时,我得到这样的两个值,{Link = www.link.url,Title = Some }
发布于 2016-02-21 00:23:09
imgTitle = elements[0].Title;基本上当你做的时候
new
{
Link = img.Attributes["src"].Value,
Title = img.Attributes["alt"].Value
}您正在创建一个具有2个属性的匿名对象。
该列表是此匿名对象的列表。
elements[0]给出了第一个对象。您可以使用elements[0].Link和elements[0].Title访问这两个属性。
发布于 2016-02-21 00:23:16
元素中真正拥有的是具有两个属性的匿名类型的列表,因此您可以访问Title,如下所示:
imgTitle = elements[0].Title;https://stackoverflow.com/questions/35530728
复制相似问题