C# 如何使用HtmlAgilityPack访问Linq.ToList()中的值

C# 如何使用HtmlAgilityPack访问Linq.ToList()中的值,c#,linq,list,html-agility-pack,C#,Linq,List,Html Agility Pack,我很抱歉,因为我仍在学习Linq和HtmlAgilityPack,但我正在尝试为已经创建的字符串值分配标题和链接。换句话说,如何访问this.ToList()的值 下面是我的代码: string imgTitle; string imgLink; private void getCaption(string txt) { HtmlDocument htmlDoc = new HtmlDocument(); htmlDoc.LoadHtml("<html><h

我很抱歉,因为我仍在学习Linq和HtmlAgilityPack,但我正在尝试为已经创建的字符串值分配标题和链接。换句话说,如何访问this.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
字符串imgTitle;
字符串imgLink;
私有void getCaption(字符串txt)
{
HtmlDocument htmlDoc=新HtmlDocument();
htmlDoc.LoadHtml(“+txt+”);
如果(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”];//我想我可以做到这一点
很抱歉提出了一个愚蠢的问题,但我还没有看到关于Linq如何工作和ToList函数的任何好的解释。当我打印元素[0]时,我会得到两个值,如下所示,{Link=www.Link.url,Title=Some Title}

imgTitle = elements[0].Title;
基本上当你这样做的时候

new
{
    Link = img.Attributes["src"].Value,
    Title = img.Attributes["alt"].Value

}
您正在创建具有2个属性的匿名对象

列表是此匿名对象的列表

elements[0]
为您提供第一个对象。您可以使用
elements[0]访问这两个属性。链接
elements[0]。标题

基本上当你这样做的时候

new
{
    Link = img.Attributes["src"].Value,
    Title = img.Attributes["alt"].Value

}
您正在创建具有2个属性的匿名对象

列表是此匿名对象的列表


elements[0]
为您提供了第一个对象。您可以使用
elements[0]访问这两个属性。链接
elements[0]。Title
元素中真正包含的是一个包含两个属性的列表,因此您可以访问
Title
,如下所示:

 imgTitle = elements[0].Title;

元素中真正包含的是具有两个属性的列表,因此您可以访问
标题
,如下所示:

 imgTitle = elements[0].Title;