Grizzly
Grizzly

Reputation: 5953

Efficient way of Comparing Counts of 3 different lists

I have 3 list objects and I need them to all have the same count.. or all be empty (Count = 0).

If one or more lists has a larger/smaller count than the other list(s) then I need to catch that.

Is there a more efficient way of writing this then doing multiple if statements?

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;
}

This is what I've started with two lists, but after writing it I am hoping for a better way.

Any help is appreciated.

Upvotes: 1

Views: 381

Answers (5)

Igor S
Igor S

Reputation: 1

Subtract firstListCount from secondListCount and thirdListCount. If all three are zero, then they all match. For example:

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

Upvotes: 0

Antoine V
Antoine V

Reputation: 7204

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

To check if they are the same count

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

Upvotes: 0

Thinko
Thinko

Reputation: 414

using System.Linq

Make an array of lists:

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

Then calculate the maximum array size:

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

And then respond if any of them is different size:

if(!lists.All(list => list.Count == maxSize))
{
    //do some stuff
}

Upvotes: 0

ProgrammingLlama
ProgrammingLlama

Reputation: 38785

What about a simple way to check an unlimited number of lists using LINQ?:

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Since zero is a perfectly valid integer number, comparing all three lists for zero count is redundant. You can rely on transitive property of equality to do the check with a simple && statement:

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

Upvotes: 3

Related Questions