I have a list:
public class myObject(){
public string Id {get;set}
public string Name {get;set}
}
var list = new List<MyObject>();
Now i want remove all dups from list:
var dupsId=
from p in list
group p by p.Id into g
where g.Count() > 1
select g.Key;
var dups= new List<MyObject>();
foreach (var id in dupsId)
{
foreach (var listItem in list.FindAll(p => p.Id== id))
{
dups.Add(listItem);
}
}
dups.ForEach(p=>list.Remove(p));
Its'r really remove all duples but i want save one. For example:
list{
{1,aaaa}
{2,bbbb}
{1,aaaa}
{3,cccc}
{1,aaaa}
{2,bbbb}
}
And i want to get:
list{
{1,aaaa}
{2,bbbb}
{3,cccc}
}
How can i modifity my code for this?
As per your comment you want to compare by ID
only, have a look at MoreLINQ and use the DistinctBy operator and select distinct objects by id. That is something like below
var distinct = items.DistinctBy( i => i.Id );
您可以按Id
对列表进行分组,然后从每个组中选择第一个元素
var distinctList = list.GroupBy(x => x.Id).Select(y => y.First());
Create equality comparer:
public sealed class myObjectEqualityComparer : IEqualityComparer<myObject>
{
public bool Equals(myObject x, myObject y)
{
// null checking here
return x.Id == y.Id;
}
public int GetHashCode(myObject obj)
{
return obj.Id.GetHashCode();
}
}
and use it in Distinct
method:
var uniqueItems = list
.Distinct(new myObjectEqualityComparer());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.