C#:字典值到哈希集的转换

发布于 2024-09-08 09:18:40 字数 185 浏览 2 评论 0原文

请建议将 Dictionary 转换为 Hashset 的最短方法

是否有内置 ToHashset() LINQ 扩展对于 IEnumerables ?

先感谢您!

Please, suggest the shortest way to convert Dictionary<Key, Value> to Hashset<Value>

Is there built-in ToHashset() LINQ extension for IEnumerables ?

Thank you in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鸵鸟症 2024-09-15 09:18:40
var yourSet = new HashSet<TValue>(yourDictionary.Values);

或者,如果您愿意,您可以构建自己的简单扩展方法来处理类型推断。那么您就不需要显式指定 HashSetT

var yourSet = yourDictionary.Values.ToHashSet();

// ...

public static class EnumerableExtensions
{
    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
    {
        return source.ToHashSet<T>(null);
    }

    public static HashSet<T> ToHashSet<T>(
        this IEnumerable<T> source, IEqualityComparer<T> comparer)
    {
        if (source == null) throw new ArgumentNullException("source");

        return new HashSet<T>(source, comparer);
    }
}
var yourSet = new HashSet<TValue>(yourDictionary.Values);

Or, if you prefer, you could knock up your own simple extension method to handle the type inferencing. Then you won't need to explicitly specify the T of the HashSet<T>:

var yourSet = yourDictionary.Values.ToHashSet();

// ...

public static class EnumerableExtensions
{
    public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
    {
        return source.ToHashSet<T>(null);
    }

    public static HashSet<T> ToHashSet<T>(
        this IEnumerable<T> source, IEqualityComparer<T> comparer)
    {
        if (source == null) throw new ArgumentNullException("source");

        return new HashSet<T>(source, comparer);
    }
}
白日梦 2024-09-15 09:18:40

new HashSet(YourDict.Values);

new HashSet<Value>(YourDict.Values);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文