我會建議你可以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