Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I elegantly write a function to get the unique property from an IEnumerable, if that exists?
    text
    copied!<p>I want to write a function that goes through an IEnumerable. For each item in the IEnumerable it gets an enum property. If everything in the IEnumerable has the same value for that property, then that value is returned. Otherwise, it returns null. I can do this, but not elegantly. Is there a Linq expression I can use? See the UniqueOption function below.</p> <pre><code>namespace Play { public enum Option { Tom, Dick, Harry } public class OptionHolder { public Option Option { get; set; } public override string ToString() { return Option.ToString(); } } public class Program { /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] private static void Main() { Program p1 = new Program(Option.Tom, Option.Dick, Option.Harry); Console.WriteLine("1: "+p1.UniqueOption()); //should be null Program p2 = new Program(Option.Dick, Option.Dick, Option.Dick); Console.WriteLine("2: " + p2.UniqueOption()); //should be Dick Program p3 = new Program(Option.Harry); Console.WriteLine("3: " + p3.UniqueOption()); //should be Harry } public Program(params Option[] options) { optionList = new List&lt;OptionHolder&gt;(); foreach (Option option in options) { OptionHolder holder = new OptionHolder(); holder.Option = option; optionList.Add(holder); } } /** * If all the OptionHolders in the Holders property have the same Option, return this. * Otherwise (there are no OptionHolders, or there is more than one but they hold different Options), return null. */ public Option? UniqueOption() { Option? option = null; foreach(OptionHolder holder in optionList) { Option o = holder.Option; if (option == null) { option = o; } else if (option != o) { return null; } } return option; } private List&lt;OptionHolder&gt; optionList; public IEnumerable&lt;OptionHolder&gt; Holders { get { return optionList; } } public override string ToString() { return String.Join(",", optionList); } } </code></pre> <p>}</p>
 

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