目前我正在使用派生自的自定义类HashSet
.在特定条件下选择项目时,代码中有一点:
var c = clusters.Where(x => x.Label != null && x.Label.Equals(someLabel));
Run Code Online (Sandbox Code Playgroud)
它工作正常,我得到了这些元素.但有没有办法可以在集合中接收该元素的索引以与ElementAt
方法一起使用,而不是整个对象?
看起来或多或少会像这样:
var c = select element index in collection under certain condition;
int index = c.ElementAt(0); //get first index
clusters.ElementAt(index).RunObjectMthod();
Run Code Online (Sandbox Code Playgroud)
是否手动迭代整个集合更好的方法?我需要补充说它是在一个更大的循环中,所以Where
对于不同的someLabel
字符串,这个子句被执行多次.
编辑
我需要这个吗?clusters
是一组文档集合的集合.文档按主题相似性分组.因此,该算法的最后一步是发现每个群集的标签.但算法并不完美,有时它会产生两个或多个具有相同标签的聚类.我想要做的只是将这些集群合并为一个集群.
Jon*_*eet 23
集合通常不具有索引.如果位置对您很重要,那么您应该使用一个List<T>
而不是(或可能一样)一组.
现在SortedSet<T>
在.NET 4中略有不同,因为它维护一个有序的值顺序.但是,它仍然没有实现IList<T>
,因此索引访问ElementAt
速度会变慢.
如果您可以提供有关您希望此功能的更多详细信息,那么它会有所帮助.你的用例目前还不是很清楚.
如果您在HashSet中保存元素,有时需要按索引获取元素,请考虑在这种情况下使用扩展方法ToList().因此,您使用HashSet的功能,然后利用索引.
HashSet<T> hashset = new HashSet<T>();
//the special situation where we need index way of getting elements
List<T> list = hashset.ToList();
//doing our special job, for example mapping the elements to EF entities collection (that was my case)
//we can still operate on hashset for example when we still want to keep uniqueness through the elements
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
35741 次 |
最近记录: |