HiveBrain v1.2.0
Get Started
← Back to all entries
principlecsharpModerate

Compare items in two lists

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
listscompareitemstwo

Problem

I have a method which compares two lists of strings. If the strings, and only the strings, from listA appear in listB, return true. Else return false.

internal bool DoIdsMatchThoseFromXml(List Ids, List XmlIds)
    {
        bool result = true;

        if (Ids.Count == XmlIds.Count)
        {
            foreach (var hwId in Ids)
            {
                if(!XmlIds.Contains(hwId))
                {
                    result = false;
                    break;
                }
            }
        }
        else
        {
            result = false;
        }

        return result;
    }


My initial unit test is passing (no edge cases etc. yet), but I was wondering if there is a more compact, but still readable, way to do it.

Solution

So let me get this straight, you are trying to determine if list A is a subset of list B?

internal bool DoIdsMatchThoseFromXml(List ids, List xmlIds)
{
    return !ids.Except(xmlIds).Any(); // A - B = {}
}


Or are you trying to see if list A is set equal to list B?

internal bool DoIdsMatchThoseFromXml(List ids, List xmlIds)
{
    return ids.Count == xmlIds.Count // assumes unique values in each list
        && new HashSet(ids).SetEquals(xmlIds);
}


I would avoid performing linear searches through this as you'd be looking at O(n*m) performance when you could be doing O(n+m). Use set operations if you can. Use HashSet if possible too.

Code Snippets

internal bool DoIdsMatchThoseFromXml(List<string> ids, List<string> xmlIds)
{
    return !ids.Except(xmlIds).Any(); // A - B = {}
}
internal bool DoIdsMatchThoseFromXml(List<string> ids, List<string> xmlIds)
{
    return ids.Count == xmlIds.Count // assumes unique values in each list
        && new HashSet<string>(ids).SetEquals(xmlIds);
}

Context

StackExchange Code Review Q#7422, answer score: 16

Revisions (0)

No revisions yet.