首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较来自同一集合的两个元素的lambda表达式的语法是什么?

比较来自同一集合的两个元素的lambda表达式的语法是什么?
EN

Stack Overflow用户
提问于 2018-12-27 22:50:31
回答 1查看 483关注 0票数 0

我试图使用lambda表达式将散列集中的每个元素与所有其他元素进行比较。

下面是我想要做的事情的一个例子。我有一类类型的隐含。蕴涵有两个性质--先于性和后继性。如果一种含义说A意味着B,另一种说B意味着C,那么就存在一种传递关系。换句话说,A暗示C。下面是我的代码的简化版本。

我试图使用lambda表达式来查找哈希集中具有传递关系的所有隐含对象。在这个类的最后一行代码中,我使用Where子句来执行查询。但是,我收到了错误信息。出于某种原因,它期望我的第二个参数(otherImplication)是int类型,而不是隐含类型。但是,正确地解释了第一个参数。如何告诉它第二个参数是什么类型?

代码语言:javascript
复制
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 ?)    

    }
}

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-28 05:15:46

试试这个:

代码语言:javascript
复制
    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)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53951702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档