开发者

Select subset of elements by comparing them with each other in LINQ

I am trying to construct a LINQ query that will take a list of elements, and based on a comparison between the elements in the list, select the ones that meet a certain criteria. Like this:

var subset = set.SomeLinqQuery((e1,e2开发者_如何转开发) => e1 == e2);

subset now contains all e1 of set where e1 == e2. Any ideas? I originally thought of just having a nested loop, but I realized that there must have been a way to do it in LINQ.


You will need a method to generate the unique pairs of items from the original set. Here’s my implementation of that:

/// <summary>
/// Returns an enumeration of tuples containing all unique pairs of distinct
/// elements from the source collection. For example, the input sequence
/// { 1, 2, 3 } yields the pairs [1,2], [1,3] and [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 that 'source' is evaluated only once
    IList<T> arr = source as IList<T> ?? source.ToList();
    for (int i = 0; i < arr.Count - 1; i++)
        for (int j = i + 1; j < arr.Count; j++)
            yield return new Tuple<T, T>(arr[i], arr[j]);
}

Now you can easily achieve what you wanted:

var results = set.UniquePairs()
                 .Where(pair => pair.Item1 == pair.Item2)
                 .Select(pair => pair.Item1);


Use a cross join

from e1 in set
from e2 in set
where e1 == e2
select e1

This gives you the identity union with the duplicates

You might want something more like this

from e1 in set
from e2 in set
where e1 != e2
where e1.key == e2.key
select e1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜