不使用LINQto对象的区别class Program{
static void Main(string[] args)
{
List<Book> books = new List<Book>
{
new Book
{
Name="C# in Depth",
Authors = new List<Author>
{
new Author
{
FirstName = "Jon", LastName="Skeet"
},
new Author
{
FirstName = "Jon", LastName="Skeet"
},
}
},
new Book
{
Name="LINQ in Action",
Authors = new List<Author>
{
new Author
{
FirstName = "Fabrice", LastName="Marguerie"
},
new Author
{
FirstName = "Steve", LastName="Eichert"
},
new Author
{
FirstName = "Jim", LastName="Wooley"
},
}
},
};
var temp = books.SelectMany(book => book.Authors).Distinct();
foreach (var author in temp)
{
Console.WriteLine(author.FirstName + " " + author.LastName);
}
Console.Read();
}}public class Book{
public string Name { get; set; }
public List<Author> Authors { get; set; }}public class Author{
public string FirstName { get; set; }
public string LastName { get; set; }
public override bool Equals(object obj)
{
return true;
//if (obj.GetType() != typeof(Author)) return false;
//else return ((Author)obj).FirstName == this.FirstName && ((Author)obj).FirstName == this.LastName;
}}这是基于“LINQ in Action”中的一个例子。清单4.16。这印了乔恩·斯基特两次。为什么?我甚至在Author类中尝试过重写等于方法。仍然不同似乎不起作用。我遗漏了什么?
3 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
Distinct()
IEqualityComparer
Equals
GetHashCode
Author
public class AuthorEquals : IEqualityComparer<Author>{ public bool Equals(Author left, Author right) { if((object)left == null && (object)right == null) { return true; } if((object)left == null || (object)right == null) { return false; } return left.FirstName == right.FirstName && left.LastName == right.LastName; } public int GetHashCode(Author author) { return (author.FirstName + author.LastName).GetHashCode(); }}
吃鸡游戏
TA贡献1829条经验 获得超7个赞
IEquatable
, Equals
GetHashCode
GroupBy
var temp = books.SelectMany(book => book.Authors) .GroupBy (y => y.FirstName + y.LastName ) .Select (y => y.First ());foreach (var author in temp){ Console.WriteLine(author.FirstName + " " + author.LastName);}
- 3 回答
- 0 关注
- 374 浏览
添加回答
举报
0/150
提交
取消