学习LINQ:快速排序快速、LINQ

2023-09-02 10:55:46 作者:゛请叫我浮云先生ヾ

我参加了暴跌,今天下午开始学习LINQ,到目前为止只是摆弄周围的LINQ的集合。其中一个我想的第一件事就是实行的qsort。

I took the plunge this afternoon and began studying LINQ, so far just mucking around with LINQ on collections. One of the first things I tried was to implement QSort.

现在 - 忽略了我的可以的只是使用一个ORDERBY而事实上,这是一个非常愚蠢的qsort的实现 - 我想出了是这样的:

Now -- ignoring the fact that I could just use an ORDERBY and that this is a very silly qsort implementation -- what I came up with was this:

public class lqsort
{
    public static List<int> QSLinq(List<int> _items)
    {
        if (_items.Count <= 1)
            return _items;

        int _pivot = _items[0];

        List<int> _less = (from _item in _items where _item < _pivot select _item).ToList();
        List<int> _same = (from _item in _items where _item == _pivot select _item).ToList();
        List<int> _greater = (from _item in _items where _item > _pivot select _item).ToList();

        return (QSLinq(_less).Concat(_same.Concat(QSLinq(_greater)))).ToList();
    }
}

这是真正的错误我是所有涉及铸造的唯一的事。是否有任何LINQ的花样我可以使用?还是我只是使用LINQ的东西,它不适合?

The only thing that really bugs me is all of the casting involved. Are there any LINQ tricks I might use? Or am I just using LINQ for things it wasn't intended for?

推荐答案

就在参数的类型更改为的IEnumerable 并使用 VAR 构建你的名单,其中代替; INT&GT; 为您的局部变量

Just change the type of the parameter to IEnumerable and use the var construct instead of your List<int> for your local variables.

这会使你的 QSLinq 方法更好,因为它会接受更多类型的参数,例如 INT [] ,以及名单,其中,INT&GT;

This will make your QSLinq method better because it will accept more types of parameters, for example int[], as well as List<int>.

请参阅新的方法:

    public static IEnumerable<int> QSLinq(IEnumerable<int> _items)
    {
        if (_items.Count() <= 1)
            return _items;

        var _pivot = _items.First();

        var _less = from _item in _items where _item < _pivot select _item;
        var _same = from _item in _items where _item == _pivot select _item;
        var _greater = from _item in _items where _item > _pivot select _item;

        return QSLinq(_less).Concat(QSLinq(_same)).Concat(QSLinq(_greater));
    }

希望这有助于。

Hope this helps.