首页 / RUBY / C#-Ruby中的LINQ功能
C#-Ruby中的LINQ功能
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#-Ruby中的LINQ功能,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1867字,纯文字阅读大概需要3分钟。
内容图文
![C#-Ruby中的LINQ功能](/upload/InfoBanner/zyjiaocheng/655/ebd83df36a3f4d3dabf0c2b115616664.jpg)
我想用Ruby编写类似C#代码的代码.
它接收候选拓扑集和世界集,并测试候选拓扑是否是相对于世界的拓扑.
在使用LINQ功能的C#中,它看起来像这样:
public static bool IsTopology<T>(IEnumerable<IEnumerable<T>> candidate, IEnumerable<T> world)
{
IEqualityComparer<IEnumerable<T>> setComparer =
new SetComparer<T>();
if (!candidate.Contains(Enumerable.Empty<T>(), setComparer) ||
!candidate.Contains(world, setComparer))
{
return false;
}
var pairs =
from x in candidate
from y in candidate
select new {x,y};
return pairs.All(pair => candidate.Contains(pair.x.Union(pair.y), setComparer) &&
candidate.Contains(pair.x.Intersect(pair.y), setComparer));
}
public class SetComparer<T> : IEqualityComparer<IEnumerable<T>>
{
public bool Equals (IEnumerable<T> x, IEnumerable<T> y)
{
return new HashSet<T>(x).SetEquals(y);
}
public int GetHashCode (IEnumerable<T> obj)
{
return 0;
}
}
我要寻找的功能如下:
>可以将相等比较器插入方法
>使用嵌套地图(和匿名类型)的能力
>将数组作为集合进行比较的能力(不是很重要,在C#中缺乏一点…)
我相信ruby具有这些功能,并且非常有兴趣了解等效代码的外观.
解决方法:
我将您的代码翻译成ruby(并重新编写了一下):
# candidate - Enumerable of Enumerable; world - Enumerable; &block - comparer of two sets.
def topology? candidate, world, &block
require 'set'
# you can pass block to this method or if no block passed it will use set comparison
comparer = block || lambda { |ary1,ary2| ary1.to_set.eql?(ary2.to_set) }
# create lambda-function to find a specified set in candidate (to reuse code)
candidate_include = lambda { |to_find| candidate.find {|item| comparer.(item, to_find) } }
return false if( !candidate_include.( []) || !candidate_include.( world) )
pairs = candidate.to_a.repeated_permutation(2)
pairs.all? do |x,y| x_set = x.to_set; y_set = y.to_set
candidate_include.(x_set & y_set) && # or x_set.intersection y_set
candidate_include.(x_set | y_set) # or x_set.union y_set
end
end
希望这可以帮助
内容总结
以上是互联网集市为您收集整理的C#-Ruby中的LINQ功能全部内容,希望文章能够帮你解决C#-Ruby中的LINQ功能所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。