c# - Select subset of elements by comparing them with each other in LINQ -
i trying construct linq query take list of elements, , based on comparison between elements in list, select ones meet criteria. this:
var subset = set.somelinqquery((e1,e2) => e1 == e2);
subset
contains e1
of set
e1 == e2
. ideas? thought of having nested loop, realized there must have been way in linq.
you need method generate unique pairs of items original set. here’s implementation of that:
/// <summary> /// returns enumeration of tuples containing unique pairs of distinct /// elements source collection. example, input sequence /// { 1, 2, 3 } yields pairs [1,2], [1,3] , [2,3] only. /// </summary> public static ienumerable<tuple<t, t>> uniquepairs<t>(this ienumerable<t> source) { if (source == null) throw new argumentnullexception("source"); return uniquepairsiterator(source); } private static ienumerable<tuple<t, t>> uniquepairsiterator<t>(ienumerable<t> source) { // make sure 'source' evaluated once ilist<t> arr = source ilist<t> ?? source.tolist(); (int = 0; < arr.count - 1; i++) (int j = + 1; j < arr.count; j++) yield return new tuple<t, t>(arr[i], arr[j]); }
now can achieve wanted:
var results = set.uniquepairs() .where(pair => pair.item1 == pair.item2) .select(pair => pair.item1);
Comments
Post a Comment