如何使这段代码更简单

本文关键字:代码 更简单 何使这 段代码 | 更新日期: 2023-09-27 18:17:39

if (spanList.Count(p => p.ClassName == "p") == 2 && (spanList.Count(p => p.ClassName == "s") == 2))
{
    lesson.lesson2Name = spanList.Where(p => p.ClassName == "p").ToList()[1].TextContent;
    lesson.lesson2Place = spanList.Where(p => p.ClassName == "s").ToList()[1].TextContent;
    lesson.lesson2Tag = adressList.Where(p => p.ClassName == "n").ToList()[1].TextContent;
    lesson.lesson2TagHref = adressList[1].GetAttribute("href");
}
else if (spanList.Count(p => p.ClassName == "p") == 4 && (spanList.Count(p => p.ClassName == "s") == 2))
{
    lesson.lesson2Name = spanList.Where(p => p.ClassName == "p").ToList()[2].TextContent;
    lesson.lesson2Place = spanList.Where(p => p.ClassName == "s").ToList()[1].TextContent;
    lesson.lesson2Tag = spanList.Where(p => p.ClassName == "p").ToList()[3].TextContent;
    lesson.lesson2TagHref = "";
}

只有列表中的索引在变化。我怎样才能使它更简单?

如何使这段代码更简单

从性能和可读性的角度来看,这看起来非常糟糕,因为每次您想了解它的一些信息时,都要遍历整个列表。

你应该试试

List<YourObject> pList = spanList.Where(p => p.ClassName == "p").ToList();
List<YourObject> sList = spanList.Where(p => p.ClassName == "s").ToList();
if (pList.Count == 2 && sList.Count == 2)
{
    lesson.lesson2Name = pList[1].TextContent;
    lesson.lesson2Place = sList[1].TextContent;
    lesson.lesson2Tag = adressList.Where(p => p.ClassName == "n").ToList()[1].TextContent;
    lesson.lesson2TagHref = adressList[1].GetAttribute("href");
}
else if (pList.Count == 4 && sList.Count == 2))
{
    lesson.lesson2Name = pList[2].TextContent;
    lesson.lesson2Place = sList[1].TextContent;
    lesson.lesson2Tag = pList.ToList()[3].TextContent;
    lesson.lesson2TagHref = "";
}
var pList = spanList.Where(p => p.ClassName == "p").ToList();
var sList = spanList.Where(p => p.ClassName == "s").ToList();
if(sList.Count == 2)
{
    string name = "";
    string tag = "";
    string taghref = "";
    switch(pList.Count)
    {
        case 2:
            name = pList[1].TextContent;
            tag = adressList.Where(p => p.ClassName == "n").ToList()[1].TextContent;
            taghref = adressList[1].GetAttribute("href");
            break;
        case 4:
            name = pList[2].TextContent;
            tag = pList[3].TextContent;
            break;
        default:
            name = "error";
            break;
    }
    lesson.lesson2Name = name;
    lesson.lesson2Place = sList[1].TextContext;
    lesson.lesson2Tag = tag;
    lesson.lesson2TagHref = taghref;
}

@Crusha K. Rool我使用了一个switch语句,就像MethodMan告诉我的那样,得到了这个。还能做得更好吗?