I have MyObject with field: id, a, b, c, e, f and I have List with 500 000 items, now how can I remove all duplicate items with of the same value of the parameter a, c, f?
I am looking for only the fastest and most efficient method.
UPDATE
I implemented comparator
Fields in my class are of different types so I use ToString()
. It is good way?
IdLoc
, IdMet
, Ser
are long?
Value
is Object
IdDataType
is long
class Comparer : IEqualityComparer<MyObject>
{
public bool Equals(MyObject x, MyObject y)
{
return x.IdLoc == y.IdLoc && x.IdMet == y.IdMet && x.Ser == y.Ser &&
x.IdDataType == y.IdDataType && x.Time == y.Time && x.Value == y.Value;
}
public int GetHashCode(MyObject obj)
{
string idLoc = obj.IdLoc.HasValue ? obj.IdLoc.ToString() : String.Empty;
string idMet = obj.IdMet.HasValue ? obj.IdMet.ToString() : String.Empty;
string ser = obj.Ser.HasValue ? obj.Ser.ToString() : String.Empty;
string value = obj.Value != null ? obj.Value.ToString() : String.Empty;
return (idLoc + idMet + ser + value + obj.IdDataType.ToString() + obj.Time.ToString()).GetHashCode();
}
}
Removing duplicates
Elements 566 890
1) Time: 2 sec
DateTime start = DateTime.Now;
List<MyObject> removed = retValTmp.Distinct(new Comparer()).ToList();
double sec = Math.Round((DateTime.Now - start).TotalSeconds, 3);
2) Time: 1.5 sec
start = DateTime.Now;
List<MyObject> retList = new List<MyObject>();
HashSet<MyObject> removed2 = new HashSet<MyObject>(new Comparer());
foreach (var item in retValTmp)
{
if (!removed2.Contains(item))
{
removed2.Add(item);
retList.Add(item);
}
}
double sec2 = Math.Round((DateTime.Now - start).TotalSeconds, 3);
4) Also I tried out this way:
start = DateTime.Now;
var removed3 = retValTmp.Select(myObj => new { myObj.IdLoc, myObj.IdMet, myObj.Ser, myObj.Value, myObj.IdDataType, myObj.Time }).Distinct().ToList();
double sec3 = Math.Round((DateTime.Now - start).TotalSeconds, 3);
Time: 0.35 sec
but returned list is not in my class, and why the number of elements in the list of 1 and 2 is different than the list of 3?
UPDATE2
public int GetDataHashCode(MyObject obj)
{
long idLoc = obj.IdLoc.HasValue ? obj.IdLoc.Value : 0;
long idMet = obj.IdMet.HasValue ? obj.IdMet.Value : 0;
long ser = obj.SerHasValue ? obj.Ser.Value : 0;
int valueHash = 0;
if (obj.Value != null)
valueHash = obj.Value.GetHashCode();
else
valueHash = valueHash.GetHashCode();
return (idLoc.GetHashCode() + idMet.GetHashCode() + ser.GetHashCode() + valueHash + obj.IdDataType.GetHashCode() + obj.Time.GetHashCode()).GetHashCode();
}
use:
foreach (MyObject daItem in retValTmp)
{
int key = GetDataHashCode(daItem);
if (!clearDict.ContainsKey(key))
clearDict.Add(key, daItem);
}
Element: 750 000
Time: 0.23 sec!