是否有一个内置的方式来比较的IEnumerable< T> (由它们的元素)?它们的、有一个、元素、方式

2023-09-03 08:11:50 作者:冷视↘天下

我想比较给定类型的元素列表,看看哪个列表是做大。

I would like to compare lists of elements of a given type, to see which list is "bigger".

new BuiltInComparer<IEnumerable<int>>().Compare(
    new[] {3,2,3}, 
    new[] {1,2,3})

...将返回1

...would return 1

new BuiltInComparer<IEnumerable<int>>().Compare(
    new[] {1,2,3}, 
    new[] {1,2,4})

...将返回-1等

...would return -1 etc

是否有这样的内置比较器?

Is there any such built in comparer?

推荐答案

我不认为有什么内置的框架 - 和埃里克说,你没有提供的比较标准。如果你的意思是比较逐元素在自然的方式,并承担了丢失的元素,比任何present元素小(即长序列比一个较短的序列,如果他们是平等的,其中可能的),那么像这将做到这一点:

I don't think there's anything built into the framework - and as Eric says, you haven't provided the comparison criteria. If you mean "compare element-wise in the natural way, and assume a 'missing' element is smaller than any present element" (i.e. a longer sequence beats a shorter subsequence if they're equal where possible) then something like this would do it:

public int SequenceCompare<T>(IEnumerable<T> source1, IEnumerable<T> source2)
{
    // TODO: Parameter validation :)
    // You could add an overload with this as a parameter
    IComparer<T> elementComparer = Comparer<T>.Default;       
    using (IEnumerator<T> iterator1 = source1.GetEnumerator())
    using (IEnumerator<T> iterator2 = source2.GetEnumerator())
    {
        while (true)
        {
            bool next1 = iterator1.MoveNext();
            bool next2 = iterator2.MoveNext();
            if (!next1 && !next2) // Both sequences finished
            {
                return 0;
            }
            if (!next1) // Only the first sequence has finished
            {
                return -1;
            }
            if (!next2) // Only the second sequence has finished
            {
                return 1;
            }
            // Both are still going, compare current elements
            int comparison = elementComparer.Compare(iterator1.Current,
                                                     iterator2.Current);
            // If elements are non-equal, we're done
            if (comparison != 0)
            {
                return comparison;
            }
        }
    }
}