c# - LINQ Distinct on multiple properties both directions -


i'm trying filter list of objects 2 of properties. object can removed if there duplicate. , if first property has same value second property , second property has same value first property.

example:

object0: id0=1a, id1=2b object1: id0=1a, id1=2b object2: id0=1a, id1=3c object3: id0=2b, id1=1a object4: id0=2b, id1=3c object5: id0=3c, id1=2b 

so following happens: object0 removes object1 , object 3 object4 removes object5

final output:

object0: id0=1a, id1=2b object2: id0=1a, id1=3c object4: id0=2b, id1=3c  

right have loops doing this, wonder if there way linq? i've tried using distinct, distinctby, , groupby. need make own compare complete this?

do way.

source   .groupby(x => new {min = math.min(x.id0, x.id1), max = math.max(x.id0, x.id1)})   .select(g => g.first()); 

tested.

    public void sillytuplestest()     {         list<tuple<string, int, int>> source = new list<tuple<string, int, int>>()         {             tuple.create("object0", 1, 2),             tuple.create("object1",1, 2),             tuple.create("object2",1, 3),             tuple.create("object3",2, 1),             tuple.create("object4",2, 3),             tuple.create("object5",3, 2)         };          var result = source             .groupby(x => new { min = math.min(x.item2, x.item3), max = math.max(x.item2, x.item3) })             .select(g => g.first());          foreach (tuple<string, int, int> resultitem in result)         {             console.writeline("{0} ({1}, {2})", resultitem.item1, resultitem.item2, resultitem.item3);         }     } 

results

object0 (1, 2) object2 (1, 3) object4 (2, 3) 

for strings, use:

source   .groupby(x =>     string.compare(x.id0, x.id1, false) < 0 ?     new {min = x.id0, max = x.id1} :     new {min = x.id1, max = x.id0})   .select(g => g.first()); 

if had unknown number of strings, use hashset<string> key , setcomparer.

iequalitycomparer<hashset<string>> comparer =    hashset<string>.createsetcomparer();  source   .groupby(x => new hashset<string>(x.getstrings()), comparer)   .select(g => g.first()); 

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -