Linq Distinct Union

Taking the union of two sets is useful and LINQ includes a query operator.

In the case where you want LINQ Union to return a distinct list of the union, You can implement an equality comparer (line 13) as shown below.

 

1: public class Contact
2: {
3:     public string Name { get; set; }
4:     public string Address { get; set; }
5:  
6:     public override string ToString()
7:     {
8:         return string.Format("{0} ---> {1}", Name, Address);
9:     }
10:     
11: }
12:  
13: public class ContactComparer : IEqualityComparer
14: {
15:     #region IEqualityComparer Members
16:  
17:     public bool Equals(Contact x, Contact y)
18:     {
19:         return x.Name == y.Name;
20:     }
21:  
22:     public int GetHashCode(Contact obj)
23:     {
24:         return obj.Name.GetHashCode();
25:     }
26:  
27:     #endregion
28: }
29:  
30: public class MyClass
31: {
32:     public static void RunSnippet()
33:     {
34:         var contacts1 = new List{
35:             new Contact { 
36:                 Name = "Guy",
37:                 Address = "Ontario"
38:             },
39:             new Contact { 
40:                 Name = "Frank",
41:                 Address = "Manitoba"
42:             },
43:             new Contact { 
44:                 Name = "Alain",
45:                 Address = "Manitoba"
46:             }
47:         };
48:  
49:         var contacts2 = new List{
50:             new Contact { 
51:                 Name = "Guy",
52:                 Address = "Ontario"
53:             },
54:             new Contact { 
55:                 Name = "Marc",
56:                 Address = "Ontario"
57:             },
58:         };
59:  
60:         var ontariocontact1 = from c1 in contacts1
61:                               where c1.Address == "Ontario"
62:                               select c1;
63:  
64:         var ontariocontact2 = from c2 in contacts2
65:                               where c2.Address == "Ontario"
66:                               select c2;
67:  
68:         var uniqueContacts = ontariocontact1.Union(ontariocontact2,
69:                              new ContactComparer());
70:         foreach (Contact contact in uniqueContacts)
71:         {
72:             Console.WriteLine(contact.ToString());
73:             System.Diagnostics.Debug.WriteLine(contact.ToString());
74:         }
75:     }

The output from this will be:

Guy ---> Ontario 
Marc ---> Ontario

Comments are closed.