c# - 比较同一集合中的两个元素的 lambda 表达式的语法是什么?
问题描述
我正在尝试使用 lambda 表达式将哈希集中的每个元素与所有其他元素进行比较。
这是我正在尝试做的一个例子。我有一类类型的暗示。蕴涵有两个属性——前因和后因。如果一个蕴涵说 A 蕴涵 B,而另一个蕴涵说 B 蕴涵 C,则存在传递关系。换句话说,A 意味着 C。这是我的代码的简化版本。
我正在尝试使用 lambda 表达式来查找哈希集中具有传递关系的所有隐含对象。在此类的最后一行代码中,我使用 Where 子句进行查询。但是,我收到错误消息。出于某种原因,它希望我的第二个参数(otherImplication)是 int 类型而不是 Implication。但是,第一个参数被正确解释。我如何告诉它第二个参数是什么类型?
public class Implication
{
public int antecedent { get; set; }
public int consequent { get; set; }
public Implication(int antecedent, int consequent)
{
this.antecedent = antecedent;
this.consequent = consequent;
}
public static void Test()
{
HashSet<Implication> hashset = new HashSet<Implication>();
hashset.Add(new Implication(1, 2)); //transitive
hashset.Add(new Implication(2, 3)); //transitive
hashset.Add(new Implication(3, 4)); //transitive
hashset.Add(new Implication(5, 6)); //NOT transitive
hashset.Add(new Implication(7, 8)); //NOT transitive
var transitives = hashset.Where((implication, otherimplication) => implication.antecedent == otherimplication.consequent);
// I'm getting the following error message for
// 'otherimplication.consequent' at the end of the previous line.
// Error CS1061 'int' does not contain a definition for
// 'consequent' and no extension method 'consequent'
// accepting a first argument of type 'int' could be
// found(are you missing a using directive or an
// assembly reference ?)
}
}
谢谢你的帮助。
解决方案
尝试这个:
var antecedents = hashset.ToLookup(x => x.antecedent);
var consequents = hashset.ToLookup(x => x.consequent);
var transitives =
hashset
.Where(x =>
antecedents[x.consequent]
.Concat(consequents[x.antecedent])
.Any());
这给了我(1, 2), (2, 3), (3, 4)
。
推荐阅读
- python - 使用 for 循环计算总字母数和特定字母数\
- excel - VBA - 检查xml节点是否存在 - 如果不使用其他节点
- javascript - 在 appendChild() 中根据当前时间显示问候语
- autokey - AutoKey 的 MATE 桌面弹出窗口类
- python - 带有 setup.py/easy_install 的 ModuleNotFoundError,但 pip 有效
- android - 在android studio中按下按钮时应用程序停止运行并退出
- php - 检查来自api php的数组中的值是否增加
- sql - 从日期表中选择每周数据
- java - android - 为什么 MediaPlayer 延迟播放 mp3 音频?
- dart - 使用 getter 和 setter 从 1-7 个整数创建字符串