2009-08-15 92 views
5

我试图使扩展方法将洗牌泛型列表集合的内容,无论其类型但林不知道要放什么东西在<之间的参数.. >作为参数。我把对象?或类型?我希望能够在我拥有的任何List集合上使用它。如何指定在C#泛型列表类型的扩展方法

谢谢!

public static void Shuffle(this List<???????> source) 
{ 
    Random rnd = new Random(); 

    for (int i = 0; i < source.Count; i++) 
    { 
     int index = rnd.Next(0, source.Count); 
     object o = source[0]; 

     source.RemoveAt(0); 
     source.Insert(index, o); 
    } 
} 

回答

11

你需要使它成为一个通用的方法:

public static void Shuffle<T>(this List<T> source) 
{ 
    Random rnd = new Random(); 

    for (int i = 0; i < source.Count; i++) 
    { 
     int index = rnd.Next(0, source.Count); 
     T o = source[0]; 

     source.RemoveAt(0); 
     source.Insert(index, o); 
    } 
} 

,将允许它与任何List<T>工作。

+4

我得学会打字速度更快。无论如何,'IList '会更一般。 – 2009-08-15 01:22:40

+0

当我尝试列出我得到的所有方法...参数“2”:无法从“对象”到“T” – Grant 2009-08-15 01:25:24

+2

@Grant转换:您需要在中途改变部分用“T”,而不是“对象“(或添加演员)。正如约翰提到的那样,使用IList 会更普遍,尽管不是所有的IList 都实现了插入,所以它可能无法正常工作。 – 2009-08-15 01:29:06

4

你让你自己的方法一般:

public static void Shuffle<T>(this List<T> source) 
3

稍微偏离主题,但Fisher-Yates shuffle会比你的方法更少的偏差和更好的性能:

public static void ShuffleInPlace<T>(this IList<T> source) 
{ 
    if (source == null) throw new ArgumentNullException("source"); 

    var rng = new Random(); 

    for (int i = 0; i < source.Count - 1; i++) 
    { 
     int j = rng.Next(i, source.Count); 

     T temp = source[j]; 
     source[j] = source[i]; 
     source[i] = temp; 
    } 
} 
0

我觉得这个解决方案快处理,因为你会随机得到你的itens,你的收藏位置将被保留以备将来使用。

namespace MyNamespace 
{ 
    public static class MyExtensions 
    { 
     public static T GetRandom<T>(this List<T> source) 
     { 
      Random rnd = new Random(); 
      int index = rnd.Next(0, source.Count); 
      T o = source[index]; 
      return o; 
     } 
    } 
} 

步骤:

  1. 创建静态类识别您的扩展
  2. 创建您扩展方法(必须是静态的)
  3. 处理您的数据。