显示未排序列表的前20个项目 [英] Displaying unsorted List's top 20 items

查看:104
本文介绍了显示未排序列表的前20个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个未排序的List<WordCount>

class WordCount
{
string word;
int count;
}

现在,我必须按计数的降序显示前20个项目.我该如何有效地编写代码?目前,我将设置一个最小整数-1(所有count> = 1),并使用内部foreach循环进行20次迭代的for循环.但是,这是一个问题,因为List中的最后几个元素的count可能为1,而前几个元素的count元素可能为1,所以现在我停留在此实现的伪代码上,以在其中显示它们命令.

And now I must display the top 20 items in descending order of count. How could I code this efficiently? Currently I would set a minimum integer of -1 (all count >= 1) and do a for loop of 20 iterations with a foreach loop inside. This is an issue though because the last few elements in the List could have count of 1 while the top few may have an element with count 1 so now I am stuck on the pseudocode for this implementation for displaying them in order.

除了List类的方法,我不能使用LINQ或其他任何东西.我个人认为我必须以某种方式使用Sort()CompareTo()完成这一壮举.这本来是要绞尽脑汁,这就是为什么必须使用给定的限制来完成它的原因.

I CANNOT use LINQ or any other things other than the methods for List class. I personally think I must accomplish this feat using Sort() and CompareTo() somehow. This is meant to be a brain twister and that is the reason why it has to be done using the given restriction.

推荐答案

这应该有效:

List<WordCount> counts = new List<WordCount>();
//Fill the list
var result = counts.OrderBy(c => c.Count).Take(20);

降序:

var result = counts.OrderByDescending(c => c.Count).Take(20);

使用自制方法:

这是一个没有任何.NET方法的解决方案.首先使用算法对列表进行排序,在这种情况下,我使用了Bubblesort(对于较大的集合效率不高).然后,从排序结果中选取第20个元素:

Using self-made methods:

Here's a solution without any .NET method. First sort the list using an algorithm, in this case I used the Bubblesort (not effeicient for larger collections). Then I take the 20 first element from the sorted result:

public class WordCount
{
    public string Word { get; set; }
    public int CharCount { get; set; }
}

public List<WordCount> SortList(List<WordCount> list)
{
    WordCount temp;
    for (int i = list.Count -1; i >= 1; i--)
    {
        for (int j = 0; j < list.Count -1; j++)
        {
            if(list[j].CharCount < list[j+1].CharCount)
            {
                temp = list[j];
                list[j] = list[j+1];
                list[j+1] = temp;
            }
        }
    }
    return list;
}

public List<WordCount> TakeNItems(int n, List<WordCount> list)
{
    List<WordCount> temp = new List<WordCount>();
    for(int i = 0; i < n; i++)
        temp.Add(list[i]);
    return temp;
}

//Usage:
var result = SortList(counts);
result = TakeNItems(20, result);

[Edit2]使用Sort()/CompareTo()

是的,也可以使用Sort()CompareTo().这需要对您的类进行几处更改,因为当您现在尝试使用Sort()时,将会得到一个InvalidOperationException.这是因为WordCount类未实现IComparable接口.实现接口意味着您将必须覆盖Equals()GetHashCode()方法并提供自己的比较器.这是基于 列表的简单实现(T).排序方法 :

Using Sort() / CompareTo()

Yes, it is also possible using Sort() and CompareTo(). This requieres a couple of changes to your class because when you try to use Sort() now, you'll get an InvalidOperationException. This is because the WordCount class does not implement the IComparable interface. Implementing the interface means you'll have to override the Equals() and GetHashCode() methods and provide your own comparer. Here's a simple implementation based on the List(T).Sort Method:

public class WordCount : IComparable<WordCount>
{
    public string Word { get; set; }
    public int CharCount { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        WordCount wc = obj as WordCount;
        return wc == null ? false : Equals(wc);
    }

    public int CompareTo(WordCount wc)
    {
        //Descending
        return wc == null ? 1 : wc.CharCount.CompareTo(CharCount);

        //Ascending
        //return wc == null ? 1 : CharCount.CompareTo(wc.CharCount);
    }

    public override int GetHashCode()
    {
        return CharCount;
    }

    public bool Equals(WordCount wc)
    {
        return wc == null ? false : CharCount.Equals(wc.CharCount);
    }
}

//Usage:
List<WordCount> counts = new List<WordCount>();
//Fill the list
counts.Sort();

对于20个项目的限制,您可以编写自己的扩展方法,该方法基本上与

And for the limit of 20 items you can write your own extension method which would basically do the same as the Enumerable.Take Method:

public static class Extensions
{
    public static IEnumerable<T> TakeN<T>(this List<T> list, int n)
    {
        for(int i = 0; i < n; i++)
            yield return list[i];
    }
}

//Usage:
List<WordCount> counts = new List<WordCount>();
//Fill the list with 10000 items and call TakeN()

IEnumerable<WordCount> smallList = counts.TakeN(20);
//Or
counts = counts.TakeN(20).ToList();

希望这可以澄清一切! ;)

Hope this clarifies it all! ;)

这篇关于显示未排序列表的前20个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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