C# 比较3个不同列表计数的有效方法
我有3个列表对象,我需要它们都具有相同的计数。。或全部为空(计数=0) 如果一个或多个列表的计数比其他列表的计数大/小,那么我需要捕捉到这一点 有没有比使用多个if语句更有效的编写方法C# 比较3个不同列表计数的有效方法,c#,performance,if-statement,C#,Performance,If Statement,我有3个列表对象,我需要它们都具有相同的计数。。或全部为空(计数=0) 如果一个或多个列表的计数比其他列表的计数大/小,那么我需要捕捉到这一点 有没有比使用多个if语句更有效的编写方法 public static bool ThreeListComparison(List<string> lstOne, List<int> lstTwo, List<decimal> lstThree) { var firstLstCount = lstOne.
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;
}
publicstaticboolThreelistComparison(列表lstOne,
列表二,列表三)
{
var firstLstCount=lstOne.Count;
var secondLstCount=lstwo.Count;
var thirdLstCount=lstThree.Count;
如果((firstLstCount==0 | | secondLstCount==0 | | thirdLstCount==0)和&(firstLstCount!=0 | | secondLstCount==0)&&
(firstLstCount==0 | | secondLstCount!=0))返回true;
if(firstLstCount==0&&secondLstCount!=0)返回false;
if(firstLstCount!=0&&secondLstCount==0)返回false;
if(firstLstCount==0 | | secondLstCount==0)返回true;
返回firstLstCount==secondLstCount;
}
这是我从两个列表开始的,但在写了之后,我希望有一个更好的方法
感谢您的帮助
var arr = new[] { firstLstCount , secondLstCount , thirdLstCount};
检查它们是否是相同的计数
return arr.Distinct().Count() == 1
因为零是一个完全有效的整数,所以比较所有三个列表的零计数是多余的。您可以依赖等式的传递属性,用一个简单的
&&
语句进行检查:
return lstOne.Count == lstTwo.Count && lstTwo.Count == lstThree.Count;
使用LINQ检查无限数量列表的简单方法是什么
public static bool ListComparison(params List<string>[] lists)
{
return lists.All(l => l.Count == lists[0].Count);
}
公共静态布尔列表比较(参数列表[]列表)
{
返回lists.All(l=>l.Count==lists[0].Count);
}
创建一个列表数组:
List<string>[] lists = new List<string>[] { firstLst, secondLst, thirdLst };
然后,如果其中任何一个大小不同,则响应:
if(!lists.All(list => list.Count == maxSize))
{
//do some stuff
}
从
secondListCount
和thirdListCount
中减去firstListCount
。如果这三个都是零,那么它们都匹配。例如:
return new[] { 0, secondLstCount - firstLstCount, thirdLstCount - firstLstCount }.All(x => x == 0)
这些列表很可能会有价值。。那么,如何检查每个列表的相同计数(可能大于等于0)?不清楚为什么不检查simply@TimSchmelter我想我太深了。。由于某种原因。。当比较对象时,我立即想到
if
statements@Tim是的,但是所有其他答案都有相同的问题:)并且列表是空的不会造成问题,因为它永远不会重复。感谢您的简单性如果它们都是5,那么它将是{return new[]{0,0,0}。all(x=>x==0)},这将正确返回TRUE
if(!lists.All(list => list.Count == maxSize))
{
//do some stuff
}
return new[] { 0, secondLstCount - firstLstCount, thirdLstCount - firstLstCount }.All(x => x == 0)