2016-07-22 15 views
0

如何在不知道集合类型的情况下从System.Collections.ICollection获取一定数量的元素?从集合中抽取一定数量的元素

伪码

System.Collections.ICollection collection = new[] { 8, 9, 10, 12 }; 

collection = collection.Take(2); 

/* collection == new[] { 8, 9 }; */ 

通常你应该能够做到这一点与System.Linq.Take当枚举

+0

'集合= collection.Take(2)'将无法编译,因为'Take'返回一个IEnumerable的'',即使是'IEnumerable',而不是'IEnumerable的'你还是不能重新分配它。 –

回答

2

你不得不Cast<T>()第一的价值观。 LINQ(Take())只适用于泛型类型:

 System.Collections.ICollection collection = new[] { 8, 9, 10, 12 }; 

     collection = collection.Cast<int>().Take(2).ToList(); 

     /* collection == new[] { 8, 9 }; */ 
+1

或者更好的是,首先使用'ICollection '(不清楚是否有一个不存在的问题)。 –

+0

我的目标是在知道类型的情况下做到这一点。 – roydukkey

+1

'.Cast ().Take(2)'? – roydukkey

-1

我想补充一个不同的方法

System.Collections.ICollection collection = new[] { 8, 9, 10, 12 }; 
var _collection = collection as IEnumerable<int>; 
var result = _collection.Take(3); 

或者

System.Collections.ICollection collection = new[] { 8, 9, 10, 12 }; 
var enunmerator = collection.GetEnumerator(); 
int count = 0; 
while (enunmerator.MoveNext() && count < 3) 
    { 
       Console.WriteLine(enunmerator.Current); 
       count++; 
    } 
+0

'ICollection'继承自'IEnumerable',但不是'IEnumerable '。因为你知道你指定的具体值,你的演员只有有效,而不是任何给定的“ICollection”(即使它恰好只有整数)。 – Servy

+0

@Servy同意,感谢您的反馈,编辑。 –

1

你可以让自己的非一般的扩展方法。

public static class ExtensionMethods 
{ 
    public static IEnumerable Take(this IEnumerable @this, int take) 
    { 

     var enumerator = @this.GetEnumerator(); 
     try 
     { 
      for (int i = 0; i < take && enumerator.MoveNext(); i++) 
      { 
       yield return enumerator.Current; 
      } 
     } 
     finally 
     { 
      var disposable = enumerator as IDisposable; 
      if(disposable != null) 
       disposable.Dispose(); 
     } 
    } 
} 

class Program 
{ 
    public static void Main(string[] args) 
    { 
     System.Collections.ICollection collection = new[] { 8, 9, 10, 12 }; 

     var result = collection.Take(2); 
     foreach (var item in result) 
     { 
      Console.WriteLine(item); 
     } 
     Console.ReadLine(); 

    } 
} 
+0

这很接近,但IEnumerable无法分配给ICollection。 – roydukkey

+0

@roydukkey你在你的问题中声明:“当你使用可枚举的”*“时,你通常可以用System.Linq.Take来做到这一点,但事实并非如此,你不能将'Take'的输出分配给一个'ICollection ',您只能将其分配给'IEnumerable '。我认为这个事实意味着你的“psudocode例子”不关心重新分配部分,只关心查询部分。如果你真的比较'IEnumerable ',那么你的''集合'应该是一个'System.Collections.IEnumerable'而不是'System.Collections.ICollection'可以比较。 –