You can solve this easily by using inheritance:
public abstract class Person
{
public string Name { get; private set; } // The setter is private because we only have to set this name when we create an instance
protected Person(string name)
{
Name = name;
}
}
public class Male : Person
{
public Male(string name) : base(name) // This constructor calls the constructor of the class it inherits and passes on the same argument
}
public class Female : Person
{
public Female(string name) : base(name)
}
public bool IsMatch(string needle, IEnumerable<Person> haystack)
{
var firstGirl = haystack.OfType<Female>().FirstOrDefault();
var firstBuy = haystack.OfType<Male>().FirstOrDefault();
return firstGirl != null &&
firstGirl.Name == needle &&
firstBoy != null &&
firstBoy.Name != needle;
}
edit:
I quite like extension methods, so I'd write the method like this:
public static class PersonExtensions
{
public static bool IsMatch(this IEnumerable<Person> haystack, string needle)
{
// same method logic in here
}
}
which you can then use like:
var people = new List<Person>();
people.Add(new Male { Name = "Bob" });
people.Add(new Female { Name = "Mary" });
var isMatch = people.IsMatch("Jane");
edit2:
It's probably even better to just have gender as a property of the Person
class:
public enum Sex
{
Male,
Female
}
public class Person
{
public string Name { get; private set; }
public Sex Gender { get; private set; }
public Person(string name, Sex gender)
{
Name = name;
Gender = gender;
}
}
and change the method to:
var firstGirl = haystack.FirstOrDefault(p => p.Gender == Gender.Female);
var firstBoy = haystack.FirstOrDefault(p => p.Gender == Gender.Male);