清爽网站模板,wordpress装饰主题,海南省建设网站首页,公民道德建设网站咨询区 Jamie#xff1a;我的类中有一个 ISet 类型的属性#xff0c;我想将 linq 查询的结果赋给它#xff0c;因为是 ISet 类型#xff0c;所以我不知道是否有高效的方法将 linq 查询结果给之#xff1f;简单来说#xff0c;就像下面这样#xff1a;ISetT foo … 咨询区 Jamie我的类中有一个 ISet 类型的属性我想将 linq 查询的结果赋给它因为是 ISet 类型所以我不知道是否有高效的方法将 linq 查询结果给之简单来说就像下面这样ISetT foo new HashedSetT();
foo (from x in bar.Items select x).SOMETHING;我在寻找 SOMETHING 这块该如何替代。回答区 Jon Skeet我觉得 .NET 没有任何内部支持也没关键大不了自己实现一个扩展方法就好参考如下代码public static class Extensions
{public static HashSetT ToHashSetT(this IEnumerableT source,IEqualityComparerT comparer null){return new HashSetT(source, comparer);}
}有了扩展方法接下来就可以这么用了。var query from i in Enumerable.Range(0, 10)select new { i, j i 1 };
var resultSet query.ToHashSet();除了用扩展方法其实你也可以用 HashSetT 构造函数比如下面这样。var query from i in Enumerable.Range(0, 10)select new { i, j i 1 };
var resultSet new HashSetint(query);Douglas你所说的 ToHashSet 扩展方法在 .NET Framework 4.7.2 和 .NET Core 2.0 中已经支持了。public static HashSetTSource ToHashSetTSource(this IEnumerableTSource source)
{return source.ToHashSet(null);
}public static HashSetTSource ToHashSetTSource(this IEnumerableTSource source, IEqualityComparerTSource comparer)
{if (source null){ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);}return new HashSetTSource(source, comparer);
}可以看到内部也是用 构造函数 的方式进行转换的。点评区 其实在很多年前我就在考虑为什么有 ToList, ToDictionary 方法而没有 ToHashSet,ToQueue,ToStack后来我想了下可能程序员在这一块使用频次太低吧不过现在加进来了给它点个赞