【问题标题】:Sorting a List of Lists by the amount of intergers of the same type they contain按列表包含的相同类型的整数数量对列表列表进行排序
【发布时间】:2015-11-11 05:47:55
【问题描述】:

大家好,我有一个列表列表,我试图根据它包含多少相同类型的 int 对其进行排序。列表列表中的每个项目都包含 4 个整数,例如:

[0,1,2,3] [0,1,1,1] [0,2,2,2] 等。我试图根据包含大多数特定 int 的列表对列表进行排序。因此,如果我想对这三个进行排序,则 [0,1,1,1] 列表将位于顶部,因为它包含三个 1 等。有人告诉我使用 linq 来执行此操作,但不知道如何使用 linq.orderby一个方法。如果有正确的方法,有人可以帮助我吗?谢谢!

public class EnemyAI : MonoBehaviour
{
    List<List<int>> listOfPaths = new List<List<int>>();

    public void sortListofLists ()
    {
        listOfPaths.OrderBy(runeList => runeList.customMethod(runeType)); //rune type is an int
    }

    public int customMethod(int sort)
    {
        int holder = 0;
        for (int i = 0; i < MethodList.Count; i++)
        {
            if (MethodList[i] == sort)
            {
                holder++;
            }
        }
        return holder;

}

【问题讨论】:

  • 为什么 { 0, 2, 2, 2 } 不如 { 0, 1, 1, 1 } 好,因为他们都有 3 个?

标签: c# linq list sorting


【解决方案1】:

只需按特定数字的数量降序排列:

var list = new List<List<int>>() 
{ 
    new List<int> { 0, 1, 2, 3 }, 
    new List<int> { 0, 1, 1, 1 }, 
    new List<int> { 0, 2, 2, 2 } 
};

var result = list.OrderByDescending(c => c.Count(y => y == 1)).ToList();

【讨论】:

  • 谢谢!效果很好 :) 不过有一件事,Count(y => y ==1) 到底是做什么的?
  • c 是内部列表,y 是 c 中的元素。所以它计算等于1的元素。
【解决方案2】:

您的问题可以分为两个子问题。

1.如何获取List中出现频率最高的整数的个数?

您可以使用以下 LINQ 查询:

int countOfMostOccurences = arr.GroupBy(x => x).Max(x => x.Count()); 

2。如何按一定的规则对 List 进行降序排序:

list = list.SortByDescending(x => rule);

现在,合并它:

List<List<int>> lists = new List<List<int>>
{
    new List<int> { 1, 2, 3, 4 },
    new List<int> { 1, 3, 3, 3 },
    new List<int> { 1, 2, 2, 3 },
    new List<int> { 1, 1, 1, 1 }
};

lists = lists.OrderByDescending(x => x.GroupBy(g => g).Max(g => g.Count())).ToList();

【讨论】:

  • 我错过了什么吗? which contains the most of a SPECIFIC int.。更多:您会感到惊讶,但是如果使用此代码,[0,2,2,2] 将出现在 [0,1,1,1] 之前,如果它出现在之前的列表中:[0,1,2,3] [0,2,2,2] [0,1,1,1]。还有一个:仅排序列表不会对列表进行排序 - 您必须将排序结果分配给某物。
  • 您的解决方案看起来不错 - 但不能解决问题。您按任何值的最大出现次数对列表进行了排序。问题是...它包含了大多数特定的int。在那种情况下,@GiorgiNakeuri 的答案是正确且简短的。
  • 是的,你是对的。此解决方案适用于按任何最频繁整数的出现次数进行排序。这个问题和它的标题只是不清楚。如果 OP 需要按特定 int 的计数对数组进行排序,那么他应该接受@GiorgiNakeuri 的答案。
  • 好像OP的contains most of a specific int不代表to start with a specific int and with it occur the most in,甚至看不到提供的代码包含这个功能。
猜你喜欢
  • 2012-07-07
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
相关资源
最近更新 更多