principlecsharpModerate
Compare items in two lists
Viewed 0 times
listscompareitemstwo
Problem
I have a method which compares two lists of strings. If the strings, and only the strings, from
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.
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?
Or are you trying to see if list A is set equal to list B?
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
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.