简体   繁体   中英

Compare two lists of objects of the same type

This is how the custom object is defined:

public class AccountDomain
{
    public string MAILDOMAIN { get; set; }
    public string ORG_NAME { get; set; }
}

This is how I am populating the List of objects:

    List<AccountDomain> mainDBAccountDomain = mainDB.GetAllAccountsAndDomains();
    List<AccountDomain> manageEngineAccountDomain = ManageEngine.GetAllAccountsAndDomains();

This code works fine - if I look at the locals windows I can see a List of Objects in both mainDBAccountDomain and manageEngineAccountDomain.

I'm struggling with the next bit, ideally I want a new list of type AccountDomain that contains all entries that are in mainDBAccountDomain and not ManageEngineAccountDomain

Any help greatly appreciated, even if it's just a pointer in the right direction!

I want a new list of type AccountDomain that contains all entries that are in mainDBAccountDomain and not ManageEngineAccountDomain

It's very simple with linq to objects, it's exactly what the Enumerable.Except function does:

var result = mainDBAccountDomain.Except(manageEngineAccountDomain).ToList();

You can pass a comparer to the Except function if you need something different from reference equality, or you could implement Equals and GetHashCode in AccountDomain (and optionally implement IEquatable<AccountDomain> on top of these).

See this explanation if you need more details about comparers.

Here's an example:

public class AccountDomainEqualityComparer : IEqualityComparer<AccountDomain>
{
    public static readonly AccountDomainEqualityComparer Instance
        = new AccountDomainEqualityComparer();

    private AccountDomainEqualityComparer()
    {
    }

    public bool Equals(AccountDomain x, AccountDomain y)
    {
        if (ReferenceEquals(x, y))
            return true;

        if (x == null || y == null)
            return false;

        return x.MAILDOMAIN == y.MAILDOMAIN
            && x.ORG_NAME == y.ORG_NAME;
    }

    public int GetHashCode(AccountDomain obj)
    {
        if (obj == null)
            return 0;

        return (obj.MAILDOMAIN ?? string.Empty).GetHashCode()
            ^ (397 * (obj.ORG_NAME ?? string.Empty).GetHashCode());
    }
}

Then, you use it like this:

var result = mainDBAccountDomain.Except(manageEngineAccountDomain, 
                                        AccountDomainEqualityComparer.Instance)
                                .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM