如何LINQ .distinct方法排序? [英] How does LINQ .distinct method sort?

查看:499
本文介绍了如何LINQ .distinct方法排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我使用LINQ阵列 .Distinct()方法。
其结果是无序的。

Let's say I'm using the LINQ array .Distinct() method. The result is unordered.

好了,一切都在预定如果你知道用来产生结果的逻辑。

Well, everything is "ordered" if you know the logic used to produce the result.

我的问题是有关结果集。将结果数组在首独特的订单或也许是最后的独特的订单?

My question is about the result set. Will the resulting array be in the "first distinct" order or perhaps the "last distinct" order?

我可以在任何顺序从来没有算?

Can I never count on any order?

这是旧的删除重复的字符串的问题,但我寻找到LINQ的解决方案。

This is the old "remove duplicate strings" problem but I'm looking into the LINQ solution.

推荐答案

假设你的意思是LINQ到对象,它基本保持了一组全到目前为止,它的返回结果,只有产生了电流项目,如果它不是招 ŧ之前已经产生。这样的结果是在原来的顺序,以除去重复项。像这样的东西(除了错误检查等):

Assuming you mean LINQ to Objects, it basically keeps a set of all the results it's returned so far, and only yields the "current" item if it hasn't been yielded before. So the results are in the original order, with duplicates removed. Something like this (except with error checking etc):

public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source)
{
    HashSet<T> set = new HashSet<T>();

    foreach (T item in source)
    {
        if (set.Add(item))
        {
            // New item, so yield it
            yield return item;
        }
    }
}

这是无法保证的 - 但我无法想象任何更合理的实现。这让鲜明的()是因为懒惰,因为它可以 - 数据只要它可以返回,只有数据的最低金额缓冲

This isn't guaranteed - but I can't imagine any more sensible implementation. This allows Distinct() to be as lazy as it can be - data is returned as soon as it can be, and only the minimum amount of data is buffered.

就凭这将是一个坏主意,但它可以是有益知道如何在当前实现(显然)的作品。特别是,你可以很容易地观察它的启动的排气原来的顺序,只需通过创建时,它产生的日志数据被鲜明,当你的的数据>鲜明

Relying on this would be a bad idea, but it can be instructive to know how the current implementation (apparently) works. In particular, you can easily observe that it starts returning data before exhausting the original sequence, simply by creating a source which logs when it produces data to be consumed by Distinct, and also logging when you receive data from Distinct.

这篇关于如何LINQ .distinct方法排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆