我有重复值的列表,我要做的是删除重复的数据。如果查看列表数据,您会看到'proj5,9,2013,FC,5558'是重复的。
更新p是ReportByProjectModel
class ReportByProjectModel
{
public string projectID { get; set; }
public int month { get; set; }
public int year { get; set; }
public string type { get; set; }
}
List<ReportByProjectModel> uniqueProjectList = p.Distinct().ToList();
System.Diagnostics.Trace.WriteLine("data list Distinct");
foreach (var d in uniqueProjectList.OrderBy(t => t.projectID).Distinct())
{
System.Diagnostics.Trace.WriteLine(d.projectID + "," + d.month + "," + d.year + "," + d.type + "," + d.value);
}
列表数据:
Proj1,4,2013,FC,1001
Proj1,5,2013,FC,664
Proj1,5,2014,FC,5850
Proj1,6,2013,FC,6651
Proj1,7,2013,FC,1785
Proj1,8,2013,FC,5907
Proj1,9,2013,FC,36582
Proj1,10,2013,FC,57170
Proj1,11,2013,FC,46002
Proj1,12,2013,FC,36758
proj2,10,2013,FC,291
proj2,10,2013,FC,291
Proj3,10,2013,FC,1440
Proj3,11,2013,FC,4105
Proj3,12,2013,FC,3223
Proj3,10,2013,FC,1440
Proj3,11,2013,FC,4105
Proj3,12,2013,FC,3223
Proj4,10,2013,FC,646
Proj4,11,2013,FC,1400
Proj4,12,2013,FC,350
Proj4,10,2013,FC,646
Proj4,11,2013,FC,1400
Proj4,12,2013,FC,350
proj5,9,2013,FC,5558
proj5,10,2013,FC,31168
proj5,11,2013,FC,29807
proj5,12,2013,FC,23329
proj5,9,2013,FC,5558
proj5,10,2013,FC,31168
proj5,11,2013,FC,29807
proj5,12,2013,FC,23329
proj6,10,2013,FC,13455
proj6,11,2013,FC,24313
proj6,12,2013,FC,10116
proj6,10,2013,FC,13455
proj6,11,2013,FC,24313
proj6,12,2013,FC,10116
Proj7,11,2013,FC,12834
Proj7,12,2013,FC,697
proj8,1,2014,FC,20000
proj8,2,2014,FC,4250
proj8,3,2014,FC,1250
proj8,4,2014,FC,2398
proj8,11,2013,FC,7339
proj8,12,2013,FC,13038
答案 0 :(得分:3)
在IEquatable<T>
上实施ReportByProjectModel
,Distinct()
应该按照您的意愿运作。
默认的相等比较器Default用于比较的值 实现IEquatable泛型接口的类型。
答案 1 :(得分:0)
Distinct()使用您要排序的对象的.Equals()和.GetHashCode()方法。
此基础实现是ReferenceEquals()。我建议在ReportByProjectModel类中使用overriding这些方法。
如果在调用.Distinct()时执行此操作,无论实体是否相同,都将基于其属性而不是其引用,并且将过滤掉重复项。
public class ReportByProjectModel
{
public string projectID { get; set; }
public int month { get; set; }
public int year { get; set; }
public string type { get; set; }
public override bool Equals(System.Object obj)
{
if (obj == null)
{
return false;
}
// If parameter is the wrong type then return false.
ReportByProjectModel p = obj as TwoDPoint;
if (p == null)
{
return false;
}
// Return true if the fields match:
return obj.projectID == p.projectID
&& obj.month == p.month
&& obj.year == p.year
&& obj.type == p.type;
}
public override int GetHashCode()
{
return string.Concat(projectID, "|", month, "|", year "|", type).GetHashCode();
}
}
我不是100%关于我的GetHashCode实现,我的想法是为这个对象创建一个唯一的键(基于使其唯一的值)。如您所知,您可能会想出一个更好的机制。
答案 2 :(得分:-1)
使用distinct。
uniquePojectList = uniqueProjectList.Distinct();
http://msdn.microsoft.com/en-us/library/vstudio/bb348436%28v=vs.100%29.aspx