gpt4 book ai didi

c# - 如何在 Distinct 中使用 lambda 表达式

转载 作者:太空狗 更新时间:2023-10-29 21:54:45 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Linq Distinct() use delegate for equality comparer

我需要通过 ID 获取唯一的 PostViewModel。如何使用 lambda 表达式做到这一点?

public IEnumerable<PostViewModel> DistinctPosts
{
get
{
return Employees
.SelectMany(e => e.PostList.Posts)
.Distinct(new PostViewModelComparer())
.ToList();
}
}

比较器:

class PostViewModelComparer : IEqualityComparer<PostViewModel>
{
#region IEqualityComparer<Contact> Members

public bool Equals(PostViewModel x, PostViewModel y)
{
return x.ID.Equals(y.ID);
}

public int GetHashCode(PostViewModel obj)
{
return obj.ID.GetHashCode();
}

#endregion
}

抱歉,这是从Use a delegate for the equality comparer for LINQ's Distinct()复制的

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com