我想编写一个函数,用于遍历IEnumerable。对于IEnumerable中的每个项目,它会获取一个枚举属性。如果IEnumerable中的所有项目都具有该属性的相同值,则返回该值。否则,返回null。我可以做到这一点,但不够优雅。是否有Linq表达式可用?请参见下面的UniqueOption函数。
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
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[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<OptionHolder>();
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<OptionHolder> optionList;
public IEnumerable<OptionHolder> Holders
{
get { return optionList; }
}
public override string ToString()
{
return String.Join(",", optionList);
}
}
}