我正在从网站上的各个页面抓取数据,我想根据元素(H1s,alt标签,元标题,那种东西)是否存在来分配总分数独特的或重复的。我想创建一个方法,可以为我抓取的每个元素执行此操作,我使用自定义类来存储。
public class PageData
{
[Key]
[Required]
public int Id { get; set; }
[Required]
public string PageUrl { get; set; }
public string Analytics { get; set; }
public bool Paginated { get; set; }
public bool Flash { get; set; }
public bool Iframe { get; set; }
public bool NoIndexFollow { get; set; }
public bool SchemaTag { get; set; }
public virtual ICollection<Platform> Platforms { get; set; }
public virtual ICollection<AltTag> AltTags { get; set; }
public virtual ICollection<Canonical> Canonicals { get; set; }
public virtual ICollection<MetaTitle> MetaTitles { get; set; }
public virtual ICollection<MetaDesc> MetaDescs { get; set; }
public virtual ICollection<BlogLocation> BlogLocations { get; set; }
public virtual ICollection<H1> H1s { get; set; }
public virtual ICollection<H2> H2s { get; set; }
public virtual ICollection<H3> H3s { get; set; }
public virtual ICollection<ViewState> ViewStates { get; set; }
}
public class H1
{
public H1() { }
public H1(int id, string h1)
{
this.Id = id;
this.H1String = h1;
}
public override string ToString()
{
return H1String;
}
[Key]
public int KeyId { get; set; }
public string H1String { get; set; }
[ForeignKey("PageData")]
public int Id { get; set; }
[ScriptIgnore]
public virtual PageData PageData { get; set; }
}
尝试分配分数的方法
public void pageCheck(SiteData site, dynamic pageObj, int lowAssignedScore, int highAssignedScore, int totalScore)
{
List<string> uniqueCheckList = new List<string>();
bool uniqueCheck = true;
foreach (PageData page in site.PageDatas)
{
if (pageObj.Count != 0)
{
foreach (var modelObj in pageObj)
{
if (uniqueCheckList.Contains(modelObj.ToString()))
{
totalScore =+ lowAssignedScore;
uniqueCheck = false;
break;
}
uniqueCheckList.Add(modelObj.ToString());
}
if (uniqueCheck)
{
totalScore += highAssignedScore;
}
}
}
我正在实例化一个新的页面对象,以传递我想要的页面的哪个元素:
PageData page = new PageData();
pageCheck(site, page.H1s, 4, 6, totalScore);
当我通过页面.H1s它将通过: {System.Collections.Generic.List&lt; Bescoured.Models.PageModels.H1&gt; }
有没有办法在c#中做我想做的事情?或者由于语言的静态性质,它不会让我?我开始创建一个特定于H1的方法,然后尝试使其成为通用的,但看起来我需要为每个元素创建一个方法。
编辑:
如果我为每个元素制作方法
,我将如何做到这一点的一个例子foreach (PageData page in site.PageDatas)
{
if (page.H1s.Count != 0)
{
foreach (H1 h1 in page.H1s)
{
if (h1s.Contains(h1.H1String))
{
totalScore += 4;
uniqueCheck = false;
break;
}
h1s.Add(h1.H1String);
}
if (uniqueCheck)
{
totalScore += 6;
}
}
}
答案 0 :(得分:0)
我看到你只使用元素的ToString()方法。为什么不传递IEnumerable&lt;串GT;进去吧?
public void pageCheck(SiteData site, IEnumerable<string> pageObj, int lowAssignedScore, int highAssignedScore, int totalScore)
用法:
pageCheck(site, page.H1s.Select(item => item.ToString()), 4, 6, totalScore);
pageCheck(site, page.AltTags.Select(item => item.ToString()), 4, 6, totalScore);
除非没有别的选择,否则我总会尽量避免动态。