本文介绍了不同的实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些人有相同的标识对象的名单,所以我想删除被复制的那些元素。
I have a List of objects that some of them have the same Ids, so I would like to remove those elements that are duplicated.
我试着用是这样的:
List<post> posts = postsFromDatabase.Distinct().ToList();
不过,这是行不通的!
But it doesn't work!
所以,我为了避免重复写了这个方法:
So I wrote this method in order to avoid the duplicates:
public List<Post> PostWithOutDuplicates(List<Post> posts)
{
List<Post> postWithOutInclude = new List<Post>();
var noDupes = posts.Select(x => x.Id).Distinct();
if (noDupes.Count() < posts.Count)
{
foreach (int idPost in noDupes)
{
postWithOutInclude.Add(posts.Where(x => x.Id == idPost).First());
}
return postWithOutInclude;
}
else
{
return posts;
}
}
如何提高性能?任何想法
Any ideas of how to improve the performance??
感谢名单提前。
推荐答案
这是很好的和容易:
List<Post> posts = posts
.GroupBy(x => x.Id)
.Select(x => x.FirstOrDefault())
但是,如果你想要写的正确方法,我建议你把它写这样的:
But if you want to write it the proper way, I'd advise you to write it like this:
public class PostComparer : IEqualityComparer<Post>
{
#region IEqualityComparer<Post> Members
public bool Equals(Post x, Post y)
{
return x.Id.Equals(y.Id);
}
public int GetHashCode(Post obj)
{
return obj.Id.GetHashCode();
}
#endregion
}
由于它会给你更多的自由,当它涉及到更多的比较。写过这个类,你可以使用它是这样的:
As it will give you more freedom when it comes to additional comparisons. having written this class you can use it like this:
List<Post> posts = postsFromDatabase.Distinct(new PostComparer()).ToList();
这篇关于不同的实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!