3 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
此代碼根據(jù)您傳遞給比較器的順序?qū)?asc 或 desc 進(jìn)行排序。它在元素上運(yùn)行 O*1,以設(shè)置能夠進(jìn)行比較的結(jié)構(gòu)。我很想知道它是否適合你更快(我認(rèn)為只適用于非常大的樹)。當(dāng)您已經(jīng)對(duì)所有內(nèi)部列表進(jìn)行排序時(shí),您不需要保留幫助字典,然后您可以取最后一個(gè)元素。
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貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是您通過二進(jìn)制比較尋找的答案,它相當(dāng)簡(jiǎn)單,因?yàn)樗鼜?sublint 和數(shù)組中取出第一個(gè)元素(正如您所尋找的那樣)。
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貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
這是你想要的?
var sortedList = myList.OrderBy(x => x.Select(y => y.Select(z => z).OrderBy(z => z))).ToList();
編輯:我忘了深入一層。導(dǎo)致該錯(cuò)誤的原因是它想要對(duì)數(shù)組對(duì)象而不是其元素進(jìn)行排序。
- 3 回答
- 0 關(guān)注
- 304 瀏覽
添加回答
舉報(bào)