Z
zydjohn
Guest
Hello:
I have some code, trying to use IEqualityComparer in LINQ:
public class Obj4Equal
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Value { get; set; }
public DateTime TimeStamp { get; set; }
}
public class ObjComparer : IEqualityComparer<Obj4Equal>
{
public bool Equals(Obj4Equal x, Obj4Equal y)
{
if (x.Name.Equals(y.Name) && (x.Value.Equals(y.Value)))
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(Obj4Equal obj)
{
unchecked
{
int hash = 100;
hash = hash * 10 + obj.ID.GetHashCode();
hash = hash * 10 + obj.Value.GetHashCode();
return hash;
}
}
}
static void Main(string[] args)
{
Obj4Equal obj1 = new Obj4Equal
{ ID = 1, Name = "A", Value = 1, TimeStamp = DateTime.Now };
Obj4Equal obj2 = new Obj4Equal
{ ID = 2, Name = "B", Value = 2, TimeStamp = DateTime.Now };
List<Obj4Equal> total_objs = new List<Obj4Equal>();
total_objs.Add(obj1);
total_objs.Add(obj2);
var search_obj1 = total_objs.Where(x == obj1).FirstOrDefault();
}
I want to find the element from a list of object, but I don't know how to use IEqualityComparer in LINQ expression.
Please advice
Continue reading...
I have some code, trying to use IEqualityComparer in LINQ:
public class Obj4Equal
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Value { get; set; }
public DateTime TimeStamp { get; set; }
}
public class ObjComparer : IEqualityComparer<Obj4Equal>
{
public bool Equals(Obj4Equal x, Obj4Equal y)
{
if (x.Name.Equals(y.Name) && (x.Value.Equals(y.Value)))
{
return true;
}
else
{
return false;
}
}
public int GetHashCode(Obj4Equal obj)
{
unchecked
{
int hash = 100;
hash = hash * 10 + obj.ID.GetHashCode();
hash = hash * 10 + obj.Value.GetHashCode();
return hash;
}
}
}
static void Main(string[] args)
{
Obj4Equal obj1 = new Obj4Equal
{ ID = 1, Name = "A", Value = 1, TimeStamp = DateTime.Now };
Obj4Equal obj2 = new Obj4Equal
{ ID = 2, Name = "B", Value = 2, TimeStamp = DateTime.Now };
List<Obj4Equal> total_objs = new List<Obj4Equal>();
total_objs.Add(obj1);
total_objs.Add(obj2);
var search_obj1 = total_objs.Where(x == obj1).FirstOrDefault();
}
I want to find the element from a list of object, but I don't know how to use IEqualityComparer in LINQ expression.
Please advice
Continue reading...