Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c# - Why SequenceEqual for List<T> returns false?

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 };

and this works fine

bool equal = list1.SequenceEqual(list2);

and returns true;

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 };
    }

and use it like this:

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

and then simply, check it

bool equal = list1.SequenceEqual(list2);

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...