热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

在C#2.0中使用HashSet,与3.5兼容-UsingHashSetinC#2.0,compatiblewith3.5

Ireallywanttousehashsetsinmyprogram.Usingadictionaryfeelsugly.Illprobablystartusin

I really want to use hashsets in my program. Using a dictionary feels ugly. I'll probably start using VS2008 with .Net 3.5 some day, so my ideal would be that even though I can't (or can I?) use hashsets in VS2005, when I start using .NET 3.5, I don't want to have to change much, if anything, in order to switch to using these hashsets.

我真的想在我的程序中使用hashsets。使用字典感觉很难看。我可能有一天会开始使用VS2008和.Net 3.5,所以我的理想是即使我不能(或者我可以?)在VS2005中使用hashsets,当我开始使用.NET 3.5时,我不想要必须改变很多,如果有的话,以便切换到使用这些hashsets。

I am wondering if anyone is aware of an existing hashset implementation designed with this in mind, or a way to use the 3.5 hashset in VS2005.

我想知道是否有人知道为此设计的现有hashset实现,或者在VS2005中使用3.5 hashset的方法。

6 个解决方案

#1


23  

You can use HashSet in a 2.0 application now - just reference System.Core.dll and you should be good to go.

您现在可以在2.0应用程序中使用HashSet - 只需参考System.Core.dll,您应该很高兴。

Note: This would require you to install the .NET 3.5 framework which is free and separate from Visual Studio. Once you have that installed you will have the new System.Core assembly which contains the HashSet type. Since the .NET frameworks versions 2.0 - 3.5 all share the same CLR you can use this assembly in your 2.0 application without any issues.

注意:这将要求您安装免费且独立于Visual Studio的.NET 3.5框架。安装完成后,您将拥有包含HashSet 类型的新System.Core程序集。由于.NET框架版本2.0 - 3.5都共享相同的CLR,因此您可以在2.0应用程序中使用此程序集而不会出现任何问题。

#2


24  

Here's one I wrote for 2.0 that uses a Dictionary internally. It's not an exact match of the 3.5 HashSet, but it does the job for me.

这是我为2.0编写的一个内部使用Dictionary 的。它不是3.5 HashSet 的精确匹配,但它为我完成了这项工作。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;

public class HashSet : ICollection, ISerializable, IDeserializationCallback
{
    private readonly Dictionary dict;

    public HashSet()
    {
        dict = new Dictionary();
    }

    public HashSet(IEnumerable items) : this()
    {
        if (items == null)
        {
            return;
        }

        foreach (T item in items)
        {
            Add(item);
        }
    }

    public HashSet NullSet { get { return new HashSet(); } }

    #region ICollection Members

    public void Add(T item)
    {
        if (null == item)
        {
            throw new ArgumentNullException("item");
        }

        dict[item] = null;
    }

    /// 
    /// Removes all items from the .
    /// 
    /// The  is read-only. 
    public void Clear()
    {
        dict.Clear();
    }

    public bool Contains(T item)
    {
        return dict.ContainsKey(item);
    }

    /// 
    /// Copies the items of the  to an , starting at a particular  index.
    /// 
    /// The one-dimensional  that is the destination of the items copied from . The  must have zero-based indexing.The zero-based index in  at which copying begins. is null. is less than 0. is multidimensional.-or- is equal to or greater than the length of .-or-The number of items in the source  is greater than the available space from  to the end of the destination .-or-Type T cannot be cast automatically to the type of the destination .
    public void CopyTo(T[] array, int arrayIndex)
    {
        if (array == null) throw new ArgumentNullException("array");
        if (arrayIndex <0 || arrayIndex >= array.Length || arrayIndex >= Count)
        {
            throw new ArgumentOutOfRangeException("arrayIndex");
        }

        dict.Keys.CopyTo(array, arrayIndex);
    }

    /// 
    /// Removes the first occurrence of a specific object from the .
    /// 
    /// 
    /// true if  was successfully removed from the ; otherwise, false. This method also returns false if  is not found in the original .
    /// 
    /// The object to remove from the .The  is read-only.
    public bool Remove(T item)
    {
        return dict.Remove(item);
    }

    /// 
    /// Gets the number of items contained in the .
    /// 
    /// 
    /// The number of items contained in the .
    /// 
    public int Count
    {
        get { return dict.Count; }
    }

    /// 
    /// Gets a value indicating whether the  is read-only.
    /// 
    /// 
    /// true if the  is read-only; otherwise, false.
    /// 
    public bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    #endregion

    public HashSet Union(HashSet set)
    {
        HashSet uniOnSet= new HashSet(this);

        if (null == set)
        {
            return unionSet;
        }

        foreach (T item in set)
        {
            if (unionSet.Contains(item))
            {
                continue;
            }

            unionSet.Add(item);
        }

        return unionSet;
    }

    public HashSet Subtract(HashSet set)
    {
        HashSet subtractSet = new HashSet(this);

        if (null == set)
        {
            return subtractSet;
        }

        foreach (T item in set)
        {
            if (!subtractSet.Contains(item))
            {
                continue;
            }

            subtractSet.dict.Remove(item);
        }

        return subtractSet;
    }

    public bool IsSubsetOf(HashSet set)
    {
        HashSet setToCompare = set ?? NullSet;

        foreach (T item in this)
        {
            if (!setToCompare.Contains(item))
            {
                return false;
            }
        }

        return true;
    }

    public HashSet Intersection(HashSet set)
    {
        HashSet intersectiOnSet= NullSet;

        if (null == set)
        {
            return intersectionSet;
        }

        foreach (T item in this)
        {
            if (!set.Contains(item))
            {
                continue;
            }

            intersectionSet.Add(item);
        }

        foreach (T item in set)
        {
            if (!Contains(item) || intersectionSet.Contains(item))
            {
                continue;
            }

            intersectionSet.Add(item);
        }

        return intersectionSet;
    }

    public bool IsProperSubsetOf(HashSet set)
    {
        HashSet setToCompare = set ?? NullSet;

        // A is a proper subset of a if the b is a subset of a and a != b
        return (IsSubsetOf(setToCompare) && !setToCompare.IsSubsetOf(this));
    }

    public bool IsSupersetOf(HashSet set)
    {
        HashSet setToCompare = set ?? NullSet;

        foreach (T item in setToCompare)
        {
            if (!Contains(item))
            {
                return false;
            }
        }

        return true;
    }

    public bool IsProperSupersetOf(HashSet set)
    {
        HashSet setToCompare = set ?? NullSet;

        // B is a proper superset of a if b is a superset of a and a != b
        return (IsSupersetOf(setToCompare) && !setToCompare.IsSupersetOf(this));
    }

    public List ToList()
    {
        return new List(this);
    }

    #region Implementation of ISerializable

    /// 
    /// Populates a  with the data needed to serialize the target object.
    /// 
    /// The  to populate with data. The destination (see ) for this serialization. The caller does not have the required permission. 
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        if (info == null) throw new ArgumentNullException("info");
        dict.GetObjectData(info, context);
    }

    #endregion

    #region Implementation of IDeserializationCallback

    /// 
    /// Runs when the entire object graph has been deserialized.
    /// 
    /// The object that initiated the callback. The functionality for this parameter is not currently implemented. 
    public void OnDeserialization(object sender)
    {
        dict.OnDeserialization(sender);
    }

    #endregion

    #region Implementation of IEnumerable

    /// 
    /// Returns an enumerator that iterates through the collection.
    /// 
    /// 
    /// A  that can be used to iterate through the collection.
    /// 
    /// 1
    public IEnumerator GetEnumerator()
    {
        return dict.Keys.GetEnumerator();
    }

    /// 
    /// Returns an enumerator that iterates through a collection.
    /// 
    /// 
    /// An  object that can be used to iterate through the collection.
    /// 
    /// 2
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion
}

#3


8  

You could use Iesi.Collections (used by NHibernate) or Mono's HashSet

您可以使用Iesi.Collections(由NHibernate使用)或Mono的HashSet

#4


3  

The C5 Library also has a HashSet implementation.

C5库还有一个HashSet实现。

#5


2  

I think PowerCollections library should fit your needs. It's an open source library that contains several collection classes that were missing in .NET, including Set, Bag, MultiDictionary etc. It runs on .NET 2.0. I've been using it for couple of years now and I'm very pleased with it.

我认为PowerCollections库应该符合您的需求。它是一个开源库,包含.NET中缺少的几个集合类,包括Set ,Bag ,MultiDictionary等。它运行在.NET 2.0上。我已经使用它几年了,我对它非常满意。

#6


1  

You can alias the Dictionary as Hashset with a using directive. Not really the same thing, but it might simplify things for you later.

您可以使用using指令将Dictionary替换为Hashset。不是一回事,但它可能会在以后简化你的事情。


推荐阅读
  • 在AngularJS中,有时需要在表单内包含某些控件,但又不希望这些控件导致表单变为脏状态。例如,当用户对表单进行修改后,表单的$dirty属性将变为true,触发保存对话框。然而,对于一些导航或辅助功能控件,我们可能并不希望它们触发这种行为。 ... [详细]
  • C/C++ 应用程序的安装与卸载解决方案
    本文介绍了如何使用Inno Setup来创建C/C++应用程序的安装程序,包括自动检测并安装所需的运行库,确保应用能够顺利安装和卸载。 ... [详细]
  • 长期从事ABAP开发工作的专业人士,在面对行业新趋势时,往往需要重新审视自己的发展方向。本文探讨了几位资深专家对ABAP未来走向的看法,以及开发者应如何调整技能以适应新的技术环境。 ... [详细]
  • 本文介绍如何通过Java代码调用阿里云短信服务API来实现短信验证码的发送功能,包括必要的依赖添加和关键代码示例。 ... [详细]
  • 页面预渲染适用于主要包含静态内容的页面。对于依赖大量API调用的动态页面,建议采用SSR(服务器端渲染),如Nuxt等框架。更多优化策略可参见:https://github.com/HaoChuan9421/vue-cli3-optimization ... [详细]
  • binlog2sql,你该知道的数据恢复工具
    binlog2sql,你该知道的数据恢复工具 ... [详细]
  • 本文详细介绍了如何在 Ubuntu 14.04 系统上搭建仅使用 CPU 的 Caffe 深度学习框架,包括环境准备、依赖安装及编译过程。 ... [详细]
  • 本文探讨了异步编程的发展历程,从最初的AJAX异步回调到现代的Promise、Generator+Co以及Async/Await等技术。文章详细分析了Promise的工作原理及其源码实现,帮助开发者更好地理解和使用这一重要工具。 ... [详细]
  • 尽管在WPF中工作了一段时间,但在菜单控件的样式设置上遇到了一些基础问题,特别是关于如何正确配置前景色和背景色。 ... [详细]
  • 本文详细介绍了 `org.apache.tinkerpop.gremlin.structure.VertexProperty` 类中的 `key()` 方法,并提供了多个实际应用的代码示例。通过这些示例,读者可以更好地理解该方法在图数据库操作中的具体用途。 ... [详细]
  • 在CentOS 7中部署Nginx并配置SSL证书
    本文详细介绍了如何在CentOS 7操作系统上安装Nginx服务器,并配置SSL证书以增强网站的安全性。适合初学者和中级用户参考。 ... [详细]
  • 本文由公众号【数智物语】(ID: decision_engine)发布,关注获取更多干货。文章探讨了从数据收集到清洗、建模及可视化的全过程,介绍了41款实用工具,旨在帮助数据科学家和分析师提升工作效率。 ... [详细]
  • iOS如何实现手势
    这篇文章主要为大家展示了“iOS如何实现手势”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“iOS ... [详细]
  • 本文探讨了如何使用Scrapy框架构建高效的数据采集系统,以及如何通过异步处理技术提升数据存储的效率。同时,文章还介绍了针对不同网站采用的不同采集策略。 ... [详细]
  • ArcBlock 发布 ABT 节点 1.0.31 版本更新
    2020年11月9日,ArcBlock 区块链基础平台发布了 ABT 节点开发平台的1.0.31版本更新,此次更新带来了多项功能增强与性能优化。 ... [详细]
author-avatar
tuiqiuq
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有