首页 > 解决方案 > 比较同一集合中的两个元素的 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 ?)    

    }
}

谢谢你的帮助。

标签: c#lambdahashset

解决方案


尝试这个:

    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)


推荐阅读