19

目前我正在使用从HashSet. 当我在特定条件下选择项目时,代码中有一点:

var c = clusters.Where(x => x.Label != null && x.Label.Equals(someLabel));

它工作正常,我得到了这些元素。但是有没有一种方法可以让我在集合中接收该元素的索引以与ElementAt方法一起使用,而不是整个对象?

它或多或少看起来像这样:

var c = select element index in collection under certain condition;
int index = c.ElementAt(0); //get first index
clusters.ElementAt(index).RunObjectMthod();

手动迭代整个集合是更好的方法吗?我需要补充一点,它在一个更大的循环中,所以这个子句针对不同的字符串Where执行了多次。someLabel

编辑

我需要这个做什么?clusters是一些文档集合的一组簇。文档按主题相似度分组。所以算法的最后一步是发现每个集群的标签。但是算法并不完美,有时它会产生两个或多个具有相同标签的集群。我想做的只是将这些集群合并成一个大集群。

4

3 回答 3

28

集合通常没有索引。如果位置对您很重要,您应该使用 aList<T>而不是(或可能以及)集合。

现在SortedSet<T>在 .NET 4 中略有不同,因为它维护排序的值顺序。但是,它仍然没有实现IList<T>,因此通过索引访问ElementAt会很慢。

如果您可以提供有关您为什么需要此功能的更多详细信息,那将有所帮助。您的用例目前还不是很清楚。

于 2010-09-30T08:33:29.730 回答
9

如果您在 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 
于 2013-05-23T20:07:04.157 回答
3

There's no such thing as an index with a hash set. One of the ways that hash sets gain efficincy in some cases is by not having to maintain them.

I also don't see what the advantage is here. If you were to obtain the index, and then use it this would be less efficient than just obtaining the element (obtaining the index would be equally efficient, and then you've an extra operation).

If you want to do several operations on the same object, just hold onto that object.

If you want to do something on several objects, do so on the basis of iterating through them (normal foreach or doing foreach on the results of a Where() etc.). If you want to do something on several objects, and then do something else on those several same objects, and you have to do it in such batches, rather than doing all the operations in the same foreach then store the results of the Where() in a List<T>.

于 2010-09-30T09:08:48.557 回答