3 回答
TA贡献1777条经验 获得超10个赞
此代码根据您传递给比较器的顺序对 asc 或 desc 进行排序。它在元素上运行 O*1,以设置能够进行比较的结构。我很想知道它是否适合你更快(我认为只适用于非常大的树)。当您已经对所有内部列表进行排序时,您不需要保留帮助字典,然后您可以取最后一个元素。
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
List<List<int>> mainList = new List<List<int>>();
List<int> newList = new List<int>();
Random rand = new Random();
for (int i = 0; i < 30; i++)
{
int ra = rand.Next(200);
if (i % 5 == 0)
{
if (newList.Count > 0)
{
newList = new List<int>();
mainList.Add(newList);
}
}
newList.Add(ra);
}
mainList.Sort( new MaxComparer(mainList, false));
foreach (List<int> oneL in mainList)
{
foreach (int oneInt in oneL)
{
Console.Write(oneInt + " ");
}
Console.WriteLine();
}
}
public class MaxComparer : IComparer<List<int>>
{
bool order = false;
Dictionary<int, int> helper = new Dictionary<int, int>();
public MaxComparer(List<List<int>> sortList, bool Order)
{
order = Order;
foreach (List<int> oneL in sortList)
{
int max = int.MinValue;
foreach (int oneInt in oneL)
{
if (max < oneInt) max = oneInt;
}
helper.Add(oneL.GetHashCode(), max);
}
}
public int Compare(List<int> x, List<int> y)
{
return helper[x.GetHashCode()].CompareTo(helper[y.GetHashCode()]) * (order ? 1:-1);
}
}
}
}
TA贡献1719条经验 获得超6个赞
这是您通过二进制比较寻找的答案,它相当简单,因为它从 sublint 和数组中取出第一个元素(正如您所寻找的那样)。
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
List<List<int[]>> mainList = new List<List<int[]>>();
Random rand = new Random();
for (int i = 0; i < 30; i++)
{
List<int[]> subList = new List<int[]>();
int limj = rand.Next(5);
for (int j = 0; j < 5 + limj; j++)
{
int limk = rand.Next(5);
int[] arrayInt = new int[limk + 5];
for (int k = 0; k < limk + 5; k++)
{
arrayInt[k] = rand.Next(200);
}
subList.Add(arrayInt);
}
mainList.Add(subList);
}
mainList.Sort(new MaxComparer(false));
foreach (List<int[]> oneL in mainList)
{
foreach (int[] arrayList in oneL)
{
foreach (int i in arrayList) Console.Write(i + " ");
Console.Write("|");
}
Console.WriteLine();
}
}
public class MaxComparer : IComparer<List<int[]>>
{
bool order = false;
public MaxComparer(bool Order)
{
order = Order;
}
public int Compare(List<int[]> x, List<int[]> y)
{
return x[0][0].CompareTo(y[0][0]) * (order ? 1 : -1);
}
}
}
}
TA贡献1805条经验 获得超9个赞
这是你想要的?
var sortedList = myList.OrderBy(x => x.Select(y => y.Select(z => z).OrderBy(z => z))).ToList();
编辑:我忘了深入一层。导致该错误的原因是它想要对数组对象而不是其元素进行排序。
- 3 回答
- 0 关注
- 252 浏览
添加回答
举报