Remove overlapping items between two List<string> collections
I have two collections of List, let's call them allFieldNames (complete set) and excludedFieldNames (partial set). I need to derive a third List that gives me all non-excluded field names. In other words, the subset list of allFieldNames NOT found in excludedFieldNames. Here is my current code:
public List<string> ListFieldNames(List<string> allFieldNames, List<string> excludedFieldNames)
{
try
{
List<string> lst = new List<string>();
foreach (string s in allFieldNames)
{
if (!excludedFieldNames.Contains(s)) lst.Add(s);
}
return lst;
开发者_如何学Python }
catch (Exception ex)
{
return null;
}
}
I know there has to be a more efficient way than manual iteration. Suggestions please.
You can use the Except
method:
return allFieldNames.Except(excludedFieldNames).ToList();
(And if you're happy to return an IEnumerable<string>
rather than a List<string>
then you could omit the final ToList
call as well.)
精彩评论