为什么序列等于列表< T>返回假? [英] Why SequenceEqual for List<T> returns false?

查看:74
本文介绍了为什么序列等于列表< T>返回假?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 sequenceEqual 当我遇到这种情况时:

Hi I have some problems with sequenceEqual when I have situation like this:

Sentence s1 = new Sentence { Text = "Hi", Order = 1 };
Sentence s2 = new Sentence { Text = "Hello", Order = 2 };
List<Sentence> list1 = new List<Sentence> { s1, s2 };
List<Sentence> list2 = new List<Sentence> { s1, s2 };

这很好用

bool equal = list1.SequenceEqual(list2);

并返回true;

但是当我有某种返回List<Sentence>的方法时 例如:

but when I have some method which returns List<Sentence> for example:

public List<Sentence> Getall()
    {
        Sentence s1 = new Sentence { Text = "Hi", Order = 1 };
        Sentence s2 = new Sentence { Text = "Hello", Order = 2 };

        return new List<Sentence> { s1, s2 };
    }

并像这样使用它:

List<Sentence> list1 = Getall();
List<Sentence> list2 = Getall();

然后简单地进行检查

bool equal = list1.SequenceEqual(list2);

它返回"false",请告诉我为什么?以及如何使其工作?

it returns 'false', please tell me why? and how to make it work?

推荐答案

您的问题是一个new Sentence { Text = "Hi", Order = 1 }不等于另一个new Sentence { Text = "Hi", Order = 1 }.尽管内容是相同的,但是您有两个单独的对象,除非您已经设计了类,否则它们将彼此不相等,除非它们实际上是相同的对象(如您的第一个示例).

Your problem is that one new Sentence { Text = "Hi", Order = 1 } is not equal to another new Sentence { Text = "Hi", Order = 1 }. Although the contents are the same, you have two separate objects, and unless you've designed your class otherwise they are not equal to each other unless they are literally the same objects (as in your first example).

您的Sentence类需要覆盖 Equals 至少 GetHashCode 点您的SequenceEquals应该可以再次工作.

Your Sentence class needs to override Equals and GetHashCode, at the very least, at which point your SequenceEquals should work again.

这篇关于为什么序列等于列表&lt; T&gt;返回假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆