比较3个不同列表的计数的有效方法

时间:2018-09-07 14:57:03

标签: c# performance if-statement

我有3个列表对象,我需要它们全部具有相同的计数..或全部为空(计数= 0)。

如果一个或多个列表的计数大于/小于其他列表,则需要捕获该列表。

是否有比编写多个if语句更有效的方式?

public static bool ThreeListComparison(List<string> lstOne,
    List<int> lstTwo, List<decimal> lstThree)
{
    var firstLstCount = lstOne.Count;
    var secondLstCount = lstTwo.Count;
    var thirdLstCount = lstThree.Count;

    if ((firstLstCount == 0 || secondLstCount == 0 || thirdLstCount == 0) && (firstLstCount != 0 || secondLstCount == 0) &&
        (firstLstCount == 0 || secondLstCount != 0)) return true;

    if (firstLstCount == 0 && secondLstCount != 0) return false;

    if (firstLstCount != 0 && secondLstCount == 0) return false;

    if (firstLstCount == 0 || secondLstCount == 0) return true;

    return firstLstCount == secondLstCount;
}

这是我从两个列表开始的内容,但是写完之后,我希望有一个更好的方法。

感谢您的帮助。

5 个答案:

答案 0 :(得分:3)

由于零是一个完全有效的整数,因此比较所有三个列表的零计数是多余的。您可以依靠相等的传递属性通过简单的&&语句进行检查:

return lstOne.Count == lstTwo.Count && lstTwo.Count == lstThree.Count;

答案 1 :(得分:0)

var arr = new[] { firstLstCount , secondLstCount , thirdLstCount};

检查它们是否相同

return arr.Distinct().Count() == 1

答案 2 :(得分:0)

使用LINQ检查无限数量的列表的简单方法呢?

public static bool ListComparison(params List<string>[] lists)
{
    return lists.All(l => l.Count == lists[0].Count);
}

答案 3 :(得分:0)

constructor(private elementRef: ElementRef) {
  this.ngHost = Object.keys(this.elementRef.nativeElement.attributes)
    .map(k => this.elementRef.nativeElement.attributes[k].name)
    .find(k => k.includes('_nghost'));
  this.ngContent = this.ngHost.replace('nghost', 'ngcontent');
}

制作一个列表数组:

using System.Linq

然后计算最大数组大小:

List<string>[] lists = new List<string>[] { firstLst, secondLst, thirdLst };

然后回答其中任何一个是否大小不同:

int maxSize = lists.Max(list => list.Count);

答案 4 :(得分:0)

firstListCountsecondListCount中减去thirdListCount。如果所有三个均为零,则它们都匹配。例如:

return new[] { 0, secondLstCount - firstLstCount, thirdLstCount - firstLstCount }.All(x => x == 0)