我试图使用lambda表达式将散列集中的每个元素与所有其他元素进行比较。
下面是我想要做的事情的一个例子。我有一类类型的隐含。蕴涵有两个性质--先于性和后继性。如果一种含义说A意味着B,另一种说B意味着C,那么就存在一种传递关系。换句话说,A暗示C。下面是我的代码的简化版本。
我试图使用lambda表达式来查找哈希集中具有传递关系的所有隐含对象。在这个类的最后一行代码中,我使用Where子句来执行查询。但是,我收到了错误信息。出于某种原因,它期望我的第二个参数(otherImplication)是int类型,而不是隐含类型。但是,正确地解释了第一个参数。如何告诉它第二个参数是什么类型?
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 ?)
}
}谢谢你的帮助。
发布于 2018-12-28 05:15:46
试试这个:
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)。
https://stackoverflow.com/questions/53951702
复制相似问题