我会建议你可以Linq-minded
,创造了良好的通用IEnumerable<T>
扩展,执行繁重的方法提升您的要求,那么你的GetRandomColor
功能更简单,你可以使用扩展方法等类似的任务。
因此,首先,定义该扩展方法:
public static IEnumerable<T> SelectRandom<T>(this IEnumerable<T> @this, int take)
{
if (@this == null)
{
return null;
}
var count = @this.Count();
if (count == 0)
{
return Enumerable.Empty<T>();
}
var rnd = new Random();
return from _ in Enumerable.Range(0, take)
let index = rnd.Next(0, count)
select @this.ElementAt(index);
}
该功能允许用户选择从任何IEnumerable<T>
零个或多个随机选择的元素。现在
您GetRandomColor
功能如下:
public static MyColor GetRandomColour()
{
return AvailableColors.SelectRandom(1).First();
}
public static MyColor GetRandomColour(IEnumerable<MyColor> except)
{
return AvailableColors.Except(except).SelectRandom(1).First();
}
第二个函数接受一个IEnumerable<MyColor>
从您的可用颜色排除这样调用这个函数,你需要选择从项目的集合MyColor
财产。既然你没有指定这个集合的类型,我觉得最好使用IEnumerable<MyColor>
而不是组成一个类型或定义一个不必要的接口。
所以,调用代码看起来像现在这样:
var myRandomColor = GetRandomColour(collectionOfItems.Select(o => o.MyColor));
或者,你可以只直接依赖于LINQ和新创建的扩展方法,并做到这一点:
var myRandomColor =
AvailableColors
.Except(collectionOfItems.Select(o => o.MyColor))
.SelectRandom(1)
.First();
此替代更具可读性和可理解性,并有助于维护代码的可维护性。请享用。
你要确实有,如果你把它作为一个领域要明确你的类型的'Random'声明。 (这让我咧嘴笑,因为我不特别喜欢'var'。) – 2010-09-09 03:25:14