首页 > 代码库 > [C#]SequenceEqual使用小结
[C#]SequenceEqual使用小结
示例:
[TestMethod()] public void DeserializeTest() { Person _personA = new Person() { Name = "YanZhiweiA", Age = 10, Address = "shanghaiA" }; Person _personB = new Person() { Name = "YanZhiweiB", Age = 11, Address = "shanghaiB" }; List<Person> _expected = new List<Person>(); _expected.Add(_personA); _expected.Add(_personB); string _jsonString = "[{‘Name‘:‘YanZhiweiA‘,‘Age‘:10,‘Address‘:‘shanghaiA‘},{‘Name‘:‘YanZhiweiB‘,‘Age‘:11,‘Address‘:‘shanghaiB‘}]"; List<Person> _result = (List<Person>)JavaScriptSerializerHelper.Deserialize<Person>(_jsonString); bool _actual = _expected.SequenceEqual(_result, new PersonCompare()); Assert.IsTrue(_actual); }<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>
public class PersonCompare : IEqualityComparer<Person> { public bool Equals(Person x, Person y) { return (x.Age == y.Age) && (x.Address == y.Address) && (x.Name == y.Name); } public int GetHashCode(Person obj) { return obj.Name.GetHashCode(); } }
说明:注意黄色背景部分代码,这样子可以利用SequenceEqual很好比较集合,希望有所帮助,谢谢!<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>
[C#]SequenceEqual使用小结