是否有内置的方法来比较IEnumerable <T>(按其元素)?

Cri*_*scu 2 .net c# comparator .net-3.5

我想比较给定类型的元素列表,以查看哪个列表 "更大".

new BuiltInComparer<IEnumerable<int>>().Compare(
    new[] {3,2,3}, 
    new[] {1,2,3})
Run Code Online (Sandbox Code Playgroud)

...将返回1

new BuiltInComparer<IEnumerable<int>>().Compare(
    new[] {1,2,3}, 
    new[] {1,2,4})
Run Code Online (Sandbox Code Playgroud)

......会返回-1等

有没有这样的内置比较器?

Jon*_*eet 10

我不认为框架中有任何内置 - 正如Eric所说,你还没有提供比较标准.如果你的意思是"以自然方式比较元素,并假设'缺失'元素小于任何现有元素"(即如果它们在可能的情况下相等则更长的序列击败更短的子序列)那么这样的事情会做它:

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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Cristi:处理`IEnumerator <T>`值非常重要.这就是最终块在迭代器块中执行的方式 - 例如,如果你有一个从文件中读取行的迭代器,处理迭代器应该关闭文件. (2认同)