Return a distinct list

arabgogs

Member
Joined
Nov 6, 2012
Messages
14
Location
Scotland
Programming Experience
5-10
Hi Guys,
I have been trying to return 2 elements from a list by a distinct value, however with the code I have at the moment i am not getting a distinct value returned, probably due to query being unable to return uniqueness with 2 elements of the list.<br>

The example of what I am trying to do is as follows.
I have a class test1 with members ele1,ele2,ele3
I have applied the following values

VB.NET:
Dim myT As New List(Of test1)
Dim x As New test1 With {.ele1 = "blah", .ele2 = "blah2", .ele3 = "blah3"}
myT.Add(x)
x = New test1 With {.ele1 = "nomatch", .ele2 = "nomatch2", .ele3 = "test"}
myT.Add(x)
x = New test1 With {.ele1 = "blah", .ele2 = "blah2", .ele3 = "blah3"}
myT.Add(x)

I follow this with the following query on the structure
VB.NET:
Dim fs2 = (From f In myT _
           Select {f.ele1, f.ele2}).Distinct

This does not return the unique structures as I wanted, it returns all objects within myT, where as I was hoping to return just the 1st and 2nd objects(x) and ignore the 3rd as it is already found in the 1st object.

any help appreciated guys
 
You are selecting arrays, that are unique objects by themselves. To select unique test1 objects you need to use Distinct on those elements, before you select member values: 'From f In myT Distinct'
Those test1 objects are also unique objects however. To overcome this you can override Equals/GetHashCode in your class to signal how your test1 objects are equal.
Another option, that is especially useful when it is difficult to change the class definition, is to use an anonymous type where you signal member keys with the Key keyword, see Key (Visual Basic)
An example applying this to your code sample:
        Dim fs2 = From f In myT
                  Select item = New With {Key f.ele1, Key f.ele2}
                  Distinct
                  Select {item.ele1, item.ele2}
 
Hi JohnH,

Thanks for the response and your solution, which works perfectly. Effectively I am thinking that the Key is creating a link between the two field akin to an index?

Thanks again. much appreciated.
 
Effectively I am thinking that the Key is creating a link between the two field akin to an index?
Yes, as explained in that article Linq Key properties is used by compiler to produce the Equals/GetHashCode overrides, those are the methods used by Distict to compare the objects for equality.
 
Back
Top