how to compare the object of two different class.

Posted by Kumar_jay99 under ASP.NET on 5/16/2011 | Points: 10 | Views : 2173 | Status : [Member] | Replies : 2
how to compare the object of two different class.




Responses

Posted by: Hemanthlaxmi on: 5/16/2011 [Member] Starter | Points: 25

Up
0
Down
Hi please refer this link
http://msdn.microsoft.com/en-us/library/ms173147.aspx

If this helps you .
Please "Mark as Answer"

Kumar_jay99, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ndebata on: 5/17/2011 [Member] Starter | Points: 25

Up
0
Down
Hi
All it depends what is the base of comparision.Lets say there are two classes as ClassA and ClassB
public class ClassA

{
public int AID { get; set; }
}
public class ClassB
{
public int BID { get; set; }
}

Now I am creating one more class called CompareA_B which implements ICompare interface.
public class CompareA_B:IComparer

{
public int Compare(object x, object y)
{
if (x is ClassA && y is ClassB)
{
ClassA obja = (ClassA)x;
ClassB objb = (ClassB)y;

if (obja.AID == objb.BID)
return 0;
else if (obja.AID > objb.BID)
return 1;
else
return -1;
}
else if (y is ClassA && x is ClassB)
{
ClassA obja = (ClassA)y;
ClassB objb = (ClassB)x;

if (obja.AID == objb.BID)
return 0;
else if (obja.AID < objb.BID)
return 1;
else
return -1;
}
else if (x is ClassA && y is ClassA)
{
ClassA obja = (ClassA)x;
ClassA objb = (ClassA)y;

if (obja.AID == objb.AID)
return 0;
else if (obja.AID > objb.AID)
return 1;
else
return -1;
}
else if (x is ClassB && y is ClassB)
{
ClassB obja = (ClassB)x;
ClassB objb = (ClassB)y;

if (obja.BID == objb.BID)
return 0;
else if (obja.BID > objb.BID)
return 1;
else
return -1;
}
else
throw new InvalidDataException("objects are not of valid type");
}
}


Then in the main program six objects are created out these two classes then added to an arraylist.

ClassA a = new ClassA { AID = 10 };
ClassA a1 = new ClassA { AID = 20 };
ClassA a2 = new ClassA { AID = 3 };

ClassB b = new ClassB { BID = 5 };
ClassB b1 = new ClassB { BID = 12 };
ClassB b2 = new ClassB { BID = 30 };

ArrayList lst = new ArrayList();
lst.Add(a);
lst.Add(b);
lst.Add(a1);
lst.Add(b1);
lst.Add(a2);
lst.Add(b2);

lst.Sort(new CompareA_B());
foreach (var item in lst)
{
if (item is ClassA)
Console.Write(((ClassA)item).AID+" ");
else
Console.Write(((ClassB)item).BID+" ");
}


The o/p of the code will be a 3 5 10 12 20 30.

Thanks,
Debata

Kumar_jay99, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response