There are a few ways you can do this. The first example I show below is a "straight" LINQ query and the second is an extension method that uses a loop. (Extension methods, in case you're not familiar, are a way of "adding" a method to class without modifying the original code; it's a Decorator Pattern).
LINQ Query approach:
int count = email.Count(c => c == '@');
This will give you the number of times that the '@' symbol appears. If count > 1
you know that there are duplicates. (Actually, you'd expect "count" to be exactly 1; if it's 0 there's no '@' symbol at all).
The downsides of the above solution are that it isn't very flexible (if you wanted to implement more rules you'd effectively be doing more loops, which isn't all that efficient) and that it'll always go through the entire string; it's not "smart enough" to know that it can stop counting once count == 2.
Here's another one:
public static class LinqExtensions
{
public static bool ContainsMultiple<T>(this IEnumerable<T> enumerable, T item)
{
bool seen = false;
foreach (T t in enumerable)
{
if (t.Equals(item))
{
if (seen) return true;
else seen = true;
}
}
return false;
}
}
You use it like this:
bool multiple = email.ContainsMultiple('@');
This solution also suffers from some degree of inflexibility (the only way to check multiple rules is to implement multiple loops/queries). However, it's "smart" enough to know that you can stop searching the string once you find a duplicate. It's also reusable.
You could also do: