TransWikia.com

Check lists are equal whilst accounting for nulls

Stack Overflow Asked on December 27, 2021

public bool Equals(Permissions that)
{
    if (Groups == null && that.Groups != null || Groups != null && that.Groups == null) return false;
    if (Users == null && that.Users != null || Users != null && that.Users == null) return false;

    if (Groups != null && Users != null)
        return Groups.SequenceEqual(that.Groups) && Users.SequenceEqual(that.Users);

    return Groups != null ? Groups.SequenceEqual(that.Groups) : Users.SequenceEqual(that.Users);
}

How can I check that both lists are equal whilst also accounting for null’s in a better way than this?

One Answer

At least you can extract collection comparison into separate method:

public static bool BothNullOrEquals<T>(IEnumerable<T> left, IEnumerable<T> right)
{
    if (left == null && right == null)
    {
        return true;
    }
    if (left != null && right != null)
    {
        return left.SequenceEqual(right);
    }
    return false;
}

public bool Equals(Permissions that)
{
     return BothNullOrEquals(Groups, that.Groups) && BothNullOrEquals(Users, that.Users);
}

Answered by Guru Stron on December 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP