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 關注
- 323 瀏覽
添加回答
舉報