how to ensure a List<String> contains each string in a sequence exactly once

c#, linq

Solution

This may not be optimal in terms of speed, but both queries are short enough to fit on a single line, and are easy to understand:

private bool ContainsAllCandidatesOnce(List<String> list1)
{
    return candidates.All(c => list1.Count(v => v == c) == 1);
}

private IEnumerable<String> MissingCandidates(List<String> list1)
{
    return candidates.Where(c => list1.Count(v => v == c) != 1);
}

Problem

Suppose I have a list of strings, like this: ``` var candidates = new List<String> { "Peter", "Chris", "Maggie", "Virginia" }; ``` Now I'd like to verify that another `List<String>`, let's call it `list1`, contains each of those candidates exactly once. How can I do that, succintly? I think I can use `Intersect()`. I also want to get the missing candidates. ``` private bool ContainsAllCandidatesOnce(List<String> list1) { ???? } private IEnumerable<String> MissingCandidates(List<String> list1) { ???? } ``` Order doesn't matter.

Original source

Related problems