Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can solve this easily by using inheritance:</p> <pre><code>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&lt;Person&gt; haystack) { var firstGirl = haystack.OfType&lt;Female&gt;().FirstOrDefault(); var firstBuy = haystack.OfType&lt;Male&gt;().FirstOrDefault(); return firstGirl != null &amp;&amp; firstGirl.Name == needle &amp;&amp; firstBoy != null &amp;&amp; firstBoy.Name != needle; } </code></pre> <p>edit:</p> <p>I quite like extension methods, so I'd write the method like this:</p> <pre><code>public static class PersonExtensions { public static bool IsMatch(this IEnumerable&lt;Person&gt; haystack, string needle) { // same method logic in here } } </code></pre> <p>which you can then use like:</p> <pre><code>var people = new List&lt;Person&gt;(); people.Add(new Male { Name = "Bob" }); people.Add(new Female { Name = "Mary" }); var isMatch = people.IsMatch("Jane"); </code></pre> <p>edit2:</p> <p>It's probably even better to just have gender as a property of the <code>Person</code> class:</p> <pre><code>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; } } </code></pre> <p>and change the method to:</p> <pre><code>var firstGirl = haystack.FirstOrDefault(p =&gt; p.Gender == Gender.Female); var firstBoy = haystack.FirstOrDefault(p =&gt; p.Gender == Gender.Male); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload